写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" ]

猜你喜欢

转载自blog.csdn.net/isFiyeheart/article/details/84069166
今日推荐