2015-10-16 85 views
0

我不知道我是否正確理解shell腳本中的句子。 這就是我想要做的句子問題(shell腳本)

#!/bin/bash 

echo Shows the numbers from 1 to 100 and their squares 
echo 

i=1 

for ((i = 1; i <= 100; i++)); do 
    exp= `expr $i \* $i` 
    echo "N: $i EXP: $exp" 
done 

它表示:「語法錯誤:壞的循環變量」

+0

我不't得到同樣的錯誤:我看到'bash:1:找不到命令','bash:4:找不到命令','bash:9:找不到命令'等,直到'10000:command not found' - 你運行的是什麼版本的bash? –

+0

...現在,你*需要擺脫'exp ='賦值中的空間,或者更好地用本地數學代替:'exp = $((i * i))' –

回答

1

你是如何運行此腳本?

您是否使用/bin/sh scriptfile.sh而不是/bin/bash scriptfile.sh/path/to/scriptfile.sh

因爲這看起來像一個dash錯誤,因爲破折號不支持算術循環語法。

+0

你意思是?我在我的終端上執行這個命令,比如「sh scripfile.sh」 – Telefang

+2

是的,'sh'不是'bash'。你的腳本使用'bash'/etc。特徵。試試'bash scriptfile.sh',它應該可以工作。一旦您賦予您的腳本可執行權限(因爲您的'#!/ bin/bash' shebang在頂部),就可以使用'./ scriptfile.sh'(等等)。 –

+0

哦對!我沒有注意到這一點。它現在有效!謝謝! – Telefang

2

如果已使腳本可執行:chmod u+x script.sh,你在呼喚它:

$ ./script.sh 

腳本將加載bash作爲腳本解釋器。
如果你使用的是類似於:sh script.sh那麼它可能是你的用過的shell是其他的東西,比如dash,ksh,zsh或其他一些連接到文件鏈接/ bin/sh的shell。

請檢查Bash是執行的shell。如果您還有問題:

的空間=之後被shell解釋爲一個新詞,將被執行。
因此,試圖執行名爲4, 9 or 16, etc.的命令將觸發command not found錯誤。

這將工作(無需使用i=1,因爲它被設置在起動):

#!/bin/bash 
echo "Shows the numbers from 1 to 100 and their squares" 
echo 
for ((i=1; i<=100; i++)); do 
    exp=`expr $i \* $i` 
    echo "N: $i EXP: $exp" 
done 

但實際上,在bash,這將是更地道:

#!/bin/bash 
echo -e "Shows the numbers from 1 to 100 and their squares\n" 
for ((i=1; i<=100; i++)); do 
    echo "N: $i EXP: $((i**2))" 
done 
+0

我不同意'{1..10}'比較習慣;它通常是避免的(我會明智地辯論),因爲它無法將擴展結果用於開始/結束值。 –

+0

@CharlesDuffy我的意思是比較習慣的是'$((i ** 2))'。但我很高興同意你對'{1..10}'的看法。已經改變。 – 2015-10-16 23:16:05