欢迎访问个人网络日志🌹🌹知行空间🌹🌹
linux shell 命令行选项
选项是跟在单破折线后面的单个字母,它能改变命令的行为。
使用命令行参数,需要每次给参数传入需要的值;而使用命令行选项,只需要从支持的选项中选出一个自己需要的选项传入就可以了。
譬如要实现一个支持加减乘除的命令,运算的数值最好写成命令行参数,因为数值有无穷多的可能,而运算的类型最好写成命令行选项,因为毕竟运算只有那么多种。
1.命令行选项的手动实现
简单选项
#!/bin/bash
echo
x=$1
shift
while [ -n "$1" ]
do
case "$1" in
-add) echo "Found the -add option"
shift
echo "x + $1 = "$[ x + $1 ] ;;
-substract) echo "Found the -substract option"
shift
echo "x - $1 = "$[ x - $1 ] ;;
-multipy) echo "Found the -multipy option"
shift
echo "x * $1 = "$[ x * $1 ] ;;
-divide) echo "Found the -divide option"
shift
echo "x / $1 = "$[ x / $1 ] ;;
*) echo "$1 is not an option" ;;
esac
shift
done
执行命令,
# bash ./cmd_opt.sh 1 -add 2
# Found the -add option
# x + 2 = 3
分离命令行参数和选项
有时候呢,需要在使用命令行参数的同时使用命令行选项,这个时候呢就需要将两者进行分离。
Linux
中处理这个问题的标准方式是用特殊字符来将二者分开,该字符会告诉脚本何时选项结束以及普通参数何时开始。对Linux
来说,这个特殊字符是双破折线(--
)
#!/bin/bash
while [ -n "$1" ]
do
case "$1" in
-a) echo "Found the -a option" ;;
-b) echo "Found the -b option";;