Shell 脚本在命令行中传递带有选项的多个参数

Shell 脚本在命令行中传递带有选项的多个参数

我有脚本,我需要像这样执行该脚本:

./create_endpoint.sh --controller-ip 10.20.20.1 --controller-name User1.

但是它的执行方式如下:

./create_endpoint.sh 10.20.20.1 User1

剧本:

CONTROLLER_IP=""
CONTROLLER_NAME=""
if [ "$#" -eq 2 ]
  then
    CONTROLLER_IP=$1
    CONTROLLER_NAME=$2
  else
    echo "Usage : create_endpoint.sh --controller-ip <Controller IP> --controller-name"
    exit 1  
fi
echo $CONTROLLER_IP
echo $CONTROLLER_NAME

答案1

我相信getopts,当您需要灵活地传递参数数量时,使用是提前使用的更好的解决方案。

这是一个有效的例子:

if (($# == 0)); then
  echo "Please pass argumensts -p <pkg1><pkg2>... -m <email1><email2>.."
  exit 2
fi
while getopts ":p:m:" opt; do
  case $opt in
    p)
      echo "-p was triggered, Parameter: $OPTARG" >&2
      PKGS=$OPTARG
      ;;
    m)
      echo "-m was triggered, Parameter: $OPTARG" >&2
      MAIL=$OPTARG
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done
echo "go thru selection"
for PKG in $PKGS;
do
 echo "ARG_PKG: $PKG"
done
echo "go thru selection email"
for M in $MAIL;
do
 echo "ARG_MAIL: $M"
done
exit 0

參考..http://wiki.bash-hackers.org/howto/getopts_tutorial

输出:

bash t -p "pkg1 pkg2 pkg3" -m "[email protected] [email protected]"
-p was triggered, Parameter: pkg1 pkg2 pkg3
-m was triggered, Parameter: [email protected] [email protected]
go thru selection
ARG_PKG: pkg1
ARG_PKG: pkg2
ARG_PKG: pkg3
go thru selection email
ARG_MAIL: [email protected]
ARG_MAIL: [email protected]

答案2

事实上,参数列表中的标志--controller-ip和计数也是如此。--controller-name

$2您应该使用和来访问参数$4,当然,还要先检查参数以确保您影响的是正确的变量。

答案3

如果你正在寻找这个,请告诉我

脚本:

[[ "$#" -ne 4 ]] && { echo "Usage : create_endpoint.sh --controller-ip <Controller IP> --controller-name"; exit 1; }
[[ "$1" = "--controller-ip" ]] &&  CONTROLLER_IP=$2
[[ "$3" = "--controller-name" ]] &&  CONTROLLER_NAME=$4

echo $CONTROLLER_IP
echo $CONTROLLER_NAME

相关内容