Shell中获取参数
如果只需要传入参数,基本上可以使用$n来取参数,注意n是从1开始的整数
$0 指向的是脚本的名字
$ cat myscript
#!/bin/bash
echo "First arg: $1"
echo "Second arg: $2"
$ ./myscript hello world
First arg: hello
Second arg: world
但是有时需要使用Option来解析参数,并打印帮助信息,下面给出一个简单的例子
#!/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"