写shell脚本踩过的坑

1. getopts获取参数是循环获取,我原本在参数a f c中调用了函数,这几个函数会用到参数x t中的变量,但是我使用脚本的时候先使用了a f c等参数,后使用了x t参数,因此函数在执行的时候找不到变量,导致程序报错。

while getopts "x:t:hafc" opt; do
	case "$opt" in
		x)	xlsx_dir=$OPTARG;;
		t)	target_path=$OPTARG;;
		h)      show_help
			exit 0
			;;
		a)	CollectAddedFiles
			CopyFiles
                        ;;
		f)	CollectAddedFiles
			;;
		c)	CopyFiles
			;;
		\?)
			echo "Invalid option: -$OPTARG"
			show_help >&2
			exit 1
			;;
	esac		
done

但是我又不想调整参数传入的顺序,于是将函数替换掉,使用字符串来控制函数的调用:

wholeProcess="false"
collectProcess="false"
copyProcess="false"

while getopts "x:t:hafc" opt; do
	case "$opt" in
		x)	xlsx_dir=$OPTARG;;
		t)	target_path=$OPTARG;;
		h)
			show_help
			exit 0
			;;
		a)	wholeProcess="true"
			;;
		f)	collectProcess="true"
			;;
		c)	copyProcess="true"
			;;
		\?)
			echo "Invalid option: -$OPTARG"
			show_help >&2
			exit 1
			;;
	esac		
done

2. shell中没有布尔变量

3. 不能把多个“与关系式”写在一个[ ]里

#wrong
if [ $wholeProcess = "true" && $collectProcess = "false" && $copyProcess = "false" ]

#right
if [ $wholeProcess = "true" ] && [ $collectProcess = "false" ] && [ $copyProcess = "false" ]

4. 逻辑表达式与[ ]之间要有空格

#wrong
if [$wholeProcess = "true"]

#right
if [ $wholeProcess = "true" ]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值