1.shell脚本数组报错 Syntax error:"(" unexpected

这与实际使用的shell版本有关。可以使用 ls -l /bin/*sh 打印出来:

可见,sh被重定向到dash,因此执行命令时使用的是dash
解决:
sudo bash ./test_season.sh
2.shell中可以直接用数字字符串和数字比较,无需用数组比较字符串再取下标!!(巨坑)
1.
for((i=0;i<12;i++))
do
if["s{month}"=="s{array_month[$i]}"]; then
season_index=$i
echo "month is ${season_index}"
fi
done
2.
echo `expr index "${array_month[@]}" ${month}`
3.
pos=`expr index "Sarray_month"is{month}""`
echo "${pos}"
4.
echo "$(expr index "s{array_month[*]}"${time})
以上通通踩坑。

它是只要子串中有 目的串中的字符 就会返回其位置。。。
如:
子串 09
目的串 01 02 03 04 05...12 (shell中数组定义空格作为间隔)
返回位置 0
注意:shell中对比字符串只能使用==、<、>、!=、-z、-n。对比字符串时,末尾一定要加上x(或者a、b等)一个字符,因为if [ $1x == "ab"x ]时如果没有了x ,并且$1是"",这个语句会翻译成if [ == "ab" ],左边相当于没有东西了,会报语法错误。或者使用[[ ]],就不需要x了。使用<或者>时,如果是用[ ],需要用转义符"\",如\>。
对比数字使用既能使用-eq、-ne、-gt、-ge、-lt、-le,也能使用==、<、>、!=。其中-eq的意思是equal,-ne是unequal,-gt是greater than,-ge是greater than or equal to,-lt是less than,-le是less than or equal to。
3.shell与py文件传参时,程序还未运行完就执行赋值,造成速度不匹配的运行错误
result=`python dht111.py 0`
解决:
python dht111.py 0
result=$?
(这个问题有时候会导致shell执行完py文件后直接退出,但后面加上mq2的控制后,改成原来这样result=`python dht111.py 0`又不会了,这也是个神奇的bug...)
4.shell与py文件传参时,shell是用list传的str

改成 sys.argv[0]后发现是str型:

改成 int(sys.argv[0])仍然报错,无法转换成int(奇怪的bug)
后用str比较来控制程序跳转


成功解决!
浙公网安备 33010602011771号