Mil*_*vić 0 linux command-line scripting bash
$ cat test15.sh
#!/bin/bash
# extracting command line options as parameters
#
echo
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found the -a option" ;;
-b) echo "Found the -b option" ;;
-c) echo "Found the -c option" ;;
*) echo "$1 is not an option" ;;
esac
shift
done
$
$ ./test15.sh -a -b -c -d
Found the -a option
Found the -b option
Found the -c option
-d is not an option
$
Run Code Online (Sandbox Code Playgroud)
-d表示作为命令行选项进行调试或删除。那么,当我们将它包含在某些脚本的命令行选项中时,为什么它不是一个选项呢?
-d代表它被编程代表的任何内容,不一定会被删除或调试。例如,curl有-d数据选项。在您的脚本中-d不是有效的选项。您的选项是-a、-b、 和-c。所有这些基本上什么也不做。
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found the -a option" ;;
-b) echo "Found the -b option" ;;
-c) echo "Found the -c option" ;;
*) echo "$1 is not an option" ;;
esac
shift
done
Run Code Online (Sandbox Code Playgroud)
要添加对-d您的支持,必须将其添加到您的案例陈述中,如下所示:
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found the -a option" ;;
-b) echo "Found the -b option" ;;
-c) echo "Found the -c option" ;;
-d) echo "Found the -d option" ;;
*) echo "$1 is not an option" ;;
esac
shift
done
Run Code Online (Sandbox Code Playgroud)
处理命令行选项的更好方法是使用getopts如下所示:
while getopts abcd opt; do
case $opt in
a) echo "Found the -a option";;
b) echo "Found the -b option";;
c) echo "Found the -c option";;
d) echo "Found the -d option";;
*) echo "Error! Invalid option!" >&2;;
esac
done
Run Code Online (Sandbox Code Playgroud)
abcd是预期参数的列表。
a- 检查-a不带参数的选项;在不支持的选项上给出错误。
a:- 检查-a带参数的选项;在不支持的选项上给出错误。该参数将被设置为OPTARG变量。
abcd- 检查选项-a, -b, -c, -d; 在不支持的选项上给出错误。
:abcd- 检查选项-a, -b, -c, -d; 消除不支持选项的错误。
opt是将当前参数设置为的变量(也在 case 语句中使用)