shell脚本中getopts与getopt的用法差异
getopts用法:
getopts在设置参数命令时,常见的是用短型命令作为参数,例如下图所示代码:
#!/bin/bash
#下面是显示帮助信息,提示有哪些命令
function show_help(){
echo "Usage: [path/to/]"$0" -t -d <path/to/create/file> -m <email_address>"
echo $'\t'"-t|--time required,set to print the current date and time;"
echo $'\t'"-d|--dictionary <path> optional,set to create a test.txt file in the directory given by <path>;"
echo $'\t'"-m|--mail <email_address> optional,set to send current script to the email given by <email_address>";
echo $'\t'"-h|--help show this help message."
}
#下面是判断你的输入是否正确,如果错误则报错
if [ $# = 0 ]
then
echo "WARNING: required at least one option!!!"
show_help
exit 1
fi
#下面则是getopts的用法,例如:-t -d -m or -h
while getopts 'htd:m:' lzopt
do
case "$lzopt" in
t)
echo -n "Date: "; date #打印时间
;;
d)
out_path="$OPTARG"
mkdir -p $out_path
echo "Create the "$USER".test.txt in "$out_path #在输入的目录下建一个txt文件
echo -n > $out_path/$USER.test.txt
;;
m)
email="$OPTARG"
echo "Send current codes to the email at "$email #发送到指定的邮箱
sendmail $email < test1.sh
;;
h)
show_help
exit 0
;;
?)
echo "ERROR: "
show_help
exit 1
;;
esac
done
下面运行getopts.sh脚本:
$ bash getopts.sh -t -d ../test -m 1234567@qq.com
[userluo@xulab ~]$ bash getopts_1.sh -t -m 19277563432@outlook.com
Date: Fri Oct 22 09:34:55 CST 2021
Send current codes to the email at 19277563432@outlook.com
sendmail: warning: inet_protocols: disabling IPv6 name/address support: Address family not supported by protocol
postdrop: warning: inet_protocols: disabling IPv6 name/address support: Address family not supported by protocol
该命令要求打印时间(-t),创建txt到上一级test文件夹中(-d),最后发送文件到输入的qq邮箱(-m).
getopt用法:
getopt相比之下,比getopts少了一个s字母,表示它是获取的单节操作命令的,因此在代码里会有一定的差异。同时,更重要的是getopt可以设置长型参数命令。例如:-t | --time.用法见下图所示:
#!/bin/bash
# getopt格式与用法,-o表示短型,-l表示长型.
ARGS=$(getopt -o "thd:" -l "time,help,document:" -n "test.sh" -- "$@")
eval set -- "${ARGS}"
while true;
do
case "${1}" in
-t|--time)
shift; #shift表示切换到下一个指令,不让程序进入死循环.
echo -n "Date: ";date
;;
-d|--document)
#因为-d命令后有输入参数,所以要2个shift,否则在运行时会进入再次输入环境.
shift 2;
out_path="$OPTARG"
mkdir -p $out_path
echo "create a the test.txt in "$out_path
echo -n > $out_path/test.txt
;;
-h|--help)
shift;
show_help
exit 1
;;
?)
shift;
echo "ERROR"
show_help
break;
exit 0
;;
--)
shift;
break;
;;
esac
done
下面进行简单的脚本运行:
$ bash getopt.sh --time --document ../test -h
[userluo@xulab codetest]$ bash getopt.sh --time
Date:
Fri Oct 22 09:39:42 CST 2021
这就是getopt与getopts在基本用法上的区别,希望对您有一定的帮助。