bash 迴圈語法錯誤 - Linux

By Hedda
at 2009-12-29T11:51
at 2009-12-29T11:51
Table of Contents
※ 引述《deepking (wnuiayldh)》之銘言:
: #!/bin/bash
: for (( i=1; i<=10; i++ )) =>> 這行 Bad for loop variable
: do
: echo $i
: done
: 看鳥哥上的語法就這個樣子
: 請問是錯在哪裡阿
A. 解決方式一: 使用 bash 啟動 script
bash test.sh
B. 解決方式二: 改寫 script, 使其可同時與 bash 與 dash 共通
---------- 以下的迥圈可同時相容 bash 及 dash ----------
#!/bin/sh
i=1
while [ $i -le 10 ];do
echo $i
i=$(($i + 1))
done
-------------------------------------------------------
註一: for ((i=1;i<=10;i++)) 只適用於 bash.
註二: 下例對於 i = i + 1 的用法, 只適用於 bash, 不適用 dash
1) ((i++))
2) i=$((i + 1))
註三: 下例對於 i = i + 1 的用法, 可同時相容於 bash 及 dash
1) i=$(($i + 1))
2) i=`expr $i + 1` --> 這寫法可同時相容於 busybox 的 ash
C. 檢查 script 的相容性:
使用 checkbashisms 來檢查你寫的 script 是否可同時相容於 bash
及 dash, 用法如下:
Terry:~/prog/script# checkbashisms for_bash.sh
possible bashism in for_bash.sh line 2 ('((' should be '$(('):
for (( i=1; i<=10; i++ ))
至於 bash 和 dash 語法上的差異, 可以參考下列網址:
http://princessleia.com/plug/2008-JP_bash_vs_dash.pdf
--
: #!/bin/bash
: for (( i=1; i<=10; i++ )) =>> 這行 Bad for loop variable
: do
: echo $i
: done
: 看鳥哥上的語法就這個樣子
: 請問是錯在哪裡阿
A. 解決方式一: 使用 bash 啟動 script
bash test.sh
B. 解決方式二: 改寫 script, 使其可同時與 bash 與 dash 共通
---------- 以下的迥圈可同時相容 bash 及 dash ----------
#!/bin/sh
i=1
while [ $i -le 10 ];do
echo $i
i=$(($i + 1))
done
-------------------------------------------------------
註一: for ((i=1;i<=10;i++)) 只適用於 bash.
註二: 下例對於 i = i + 1 的用法, 只適用於 bash, 不適用 dash
1) ((i++))
2) i=$((i + 1))
註三: 下例對於 i = i + 1 的用法, 可同時相容於 bash 及 dash
1) i=$(($i + 1))
2) i=`expr $i + 1` --> 這寫法可同時相容於 busybox 的 ash
C. 檢查 script 的相容性:
使用 checkbashisms 來檢查你寫的 script 是否可同時相容於 bash
及 dash, 用法如下:
Terry:~/prog/script# checkbashisms for_bash.sh
possible bashism in for_bash.sh line 2 ('((' should be '$(('):
for (( i=1; i<=10; i++ ))
至於 bash 和 dash 語法上的差異, 可以參考下列網址:
http://princessleia.com/plug/2008-JP_bash_vs_dash.pdf
--
Tags:
Linux
All Comments

By Frederic
at 2009-12-30T02:55
at 2009-12-30T02:55
Related Posts
ncu的sourceforge mirror何時才會修好?

By Anonymous
at 2009-12-29T11:41
at 2009-12-29T11:41
請問tcpdump跟awk這個指令

By Callum
at 2009-12-29T09:09
at 2009-12-29T09:09
請問tcpdump跟awk這個指令

By Franklin
at 2009-12-29T04:31
at 2009-12-29T04:31
請問安裝套件會影響到其他人嗎?

By Susan
at 2009-12-29T03:38
at 2009-12-29T03:38
請問tcpdump跟awk這個指令

By Doris
at 2009-12-29T01:27
at 2009-12-29T01:27