shell传递命令行参数并设置默认值:
测试shell脚本xx.sh,有1个无默认值参数,3个有默认参数值:

arg1=$1  # 无默认值
arg2=${2:-default_arg2}  # 设置默认值为/default_arg2
arg3=${3:-default_arg3}  # 设置默认值为/default_arg3
arg4=${4:-default_arg4}  # 设置默认值为/default_arg4
echo $arg1 $arg2 $arg3 $arg4

使用方法:

# 参数都未设定,arg1为空,其他为默认:
$ sh xx.sh
default_arg2 default_arg3 default_arg4

# 设定第一个参数,其他默认:
$ sh xx.sh tst1
tst1 default_arg2 default_arg3 default_arg4

$ sh xx.sh tst1 tst2
tst1 tst2 default_arg3 default_arg4

# 如果部分使用默认值,需要用单引号('')或双引号("")预留对应参数位置
$ sh xx.sh tst1 tst2 '' tst4
tst1 tst2 default_arg3 tst4
$ sh xx.sh tst1 tst2 "" tst4
tst1 tst2 default_arg3 tst4

# 只是用空格,参数的对应是错误的!!!
$ sh xx.sh tst1 tst2   tst4
tst1 tst2 tst4 default_arg4
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐