2012-11-16

Shell Script 誤報問題

部分 Linux 發行版,為了提升啟動速度將,以 /bin/dash 執行
導致部分 /bin/bash 的功能無法使用

例如使用 Numeric For Loop
for ((i=0;i<10;i+=1)); do
    echo "${i}";
done
會發生 Bad for loop variable
原因是 /bin/dash 沒有 Numeric For Loop 語法,導致錯誤
但使用 /bin/bash ,這種 Numeric For Loop 卻是有效
要令 Numeric For Loop 生效,便需要將 /bin/dash 重新定向為 /bin/bash
輸入
sudo dpkg-reconfigure dash
見下文
在選項中選擇 No 將 dash 設定為非預設的 /bin/sh

不過若必須使用 Numeric Loop 但沒有權限重設 /bin/dash
以 While Loop 亦可以達到相同效果,亦不需要設定 /bin/dash
i=0;
while [ "${i}" -lt '10' ]; do
    echo "${i}";
done
值得留意的是
Numeric Foor Loop 是允許直接使用 < 及 >
但在 Shell Script 中 < 及 > 是一種 redirect 功能符號
在 if while until 等功能中不能使用 < 及 >
需要使用 -lt 代替 < , -gt 代替 > ,否則會發生語法錯誤

沒有留言 :

張貼留言