Answers:
shell命令和该命令的任何参数显示为编号的 shell变量:$0有命令本身的字符串值,像script,./script,/home/user/bin/script或什么的。任何参数显示为"$1","$2","$3"等等。参数的数量在shell变量中"$#"。
解决此问题的常用方法包括shell命令getopts和shift。getopts与C getopt()库函数非常相似。shift移动值$2到$1,$3到$2,等等; $#递减。代码最终查看的值"$1",然后使用case… esac决定某项操作,然后执行a shift移至$1下一个参数。它只需要检查$1,也许$#。
$/shellscriptname.sh argument1 argument2 argument3 您还可以将一个Shell脚本的输出作为参数传递给另一个Shell脚本。
$/shellscriptname.sh "$(secondshellscriptname.sh)"在shell脚本中,您可以访问带有数字的参数,例如$1第一个参数和$2第二个参数等等。
在bash脚本上,我个人喜欢使用以下脚本来设置参数:
#!/bin/bash
helpFunction()
{
   echo ""
   echo "Usage: $0 -a parameterA -b parameterB -c parameterC"
   echo -e "\t-a Description of what is parameterA"
   echo -e "\t-b Description of what is parameterB"
   echo -e "\t-c Description of what is parameterC"
   exit 1 # Exit script after printing help
}
while getopts "a:b:c:" opt
do
   case "$opt" in
      a ) parameterA="$OPTARG" ;;
      b ) parameterB="$OPTARG" ;;
      c ) parameterC="$OPTARG" ;;
      ? ) helpFunction ;; # Print helpFunction in case parameter is non-existent
   esac
done
# Print helpFunction in case parameters are empty
if [ -z "$parameterA" ] || [ -z "$parameterB" ] || [ -z "$parameterC" ]
then
   echo "Some or all of the parameters are empty";
   helpFunction
fi
# Begin script in case all parameters are correct
echo "$parameterA"
echo "$parameterB"
echo "$parameterC"使用这种结构,我们不必依赖参数的顺序,因为我们要为每个参数定义一个关键字母。同样,在错误定义参数的所有时间都会打印帮助功能。当我们有许多带有不同参数的脚本要处理时,这非常有用。它的工作方式如下:
$ ./myscript -a "String A" -b "String B" -c "String C"
String A
String B
String C
$ ./myscript -a "String A" -c "String C" -b "String B"
String A
String B
String C
$ ./myscript -a "String A" -c "String C" -f "Non-existent parameter"
./myscript: illegal option -- f
Usage: ./myscript -a parameterA -b parameterB -c parameterC
    -a Description of what is parameterA
    -b Description of what is parameterB
    -c Description of what is parameterC
$ ./myscript -a "String A" -c "String C"
Some or all of the parameters are empty
Usage: ./myscript -a parameterA -b parameterB -c parameterC
    -a Description of what is parameterA
    -b Description of what is parameterB
    -c Description of what is parameterC在shell脚本中; 它成为变量名$ 1。第二个单词变为变量名$ 2,依此类推。
cat << 'EOF' > test
echo "First arg: $1"
echo "Second arg: $2"
echo "List of all arg: $@"
EOF
sh test hello world可以在http://heirloom.sourceforge.net/sh/sh.1.html的Shell(sh)手册中找到更多信息。
如果您熟悉Python argparse,并且不介意调用python解析bash参数,请使用bash argparse(https://github.com/mattbryson/bash-arg-parse),
在这里看到相同的答案:https : //stackoverflow.com/questions/7069682/how-to-get-arguments-with-flags-in-bash-script/50181287#50181287
getopt()是一个非常成熟的标准,但是getopt在发行版/平台之间,可执行文件并不相同。我现在是一个完全转换的getopts用户,因为它是POSIX标准。它dash也很好用,这是我首选的脚本外壳