ubuntu16.06輸出循環數字:
命令行中:
for i in {1..5}; do echo $i; done
#result
1
2
3
4
5
但是將for i in {1..5}; do echo $i; done,寫到shell腳本中執行時卻輸出,
{1..5}
另外,命令行:
for ((i=1;i<=5;i++)) do echo $i; done
#result
1
2
3
4
5
但是在shell腳本中執行時報錯:Syntax error: Bad for loop variable。
原因:從 ubuntu 6.10 開始,ubuntu 就將先前默認的bash shell 更換成了dash shell;其表現爲 /bin/sh 鏈接倒了/bin/dash而不是傳統的/bin/bash。在ubuntu下打印:echo $SHELL 輸出bash,會誤導人。
dash不支持這種C語言格式的for循環寫法。
解決辦法:
1、將默認shell更改爲bash。(bash支持C語言格式的for循環)
sudo dpkg-reconfigure dash
在選擇項中選No
2、直接使用bash檢測:
bash -n xxx.sh
3、爲了確保shell腳本的可移植性,直接更改shell腳本,使用shell支持的for循環格式:
for a in `seq $num`
參考:https://blog.csdn.net/liuqinglong_along/article/details/52191382