我不知道我是否正確理解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
它表示:「語法錯誤:壞的循環變量」
我不知道我是否正確理解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
它表示:「語法錯誤:壞的循環變量」
你是如何運行此腳本?
您是否使用/bin/sh scriptfile.sh
而不是/bin/bash scriptfile.sh
或/path/to/scriptfile.sh
?
因爲這看起來像一個dash
錯誤,因爲破折號不支持算術循環語法。
如果已使腳本可執行: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
我不同意'{1..10}'比較習慣;它通常是避免的(我會明智地辯論),因爲它無法將擴展結果用於開始/結束值。 –
@CharlesDuffy我的意思是比較習慣的是'$((i ** 2))'。但我很高興同意你對'{1..10}'的看法。已經改變。 – 2015-10-16 23:16:05
我不't得到同樣的錯誤:我看到'bash:1:找不到命令','bash:4:找不到命令','bash:9:找不到命令'等,直到'10000:command not found' - 你運行的是什麼版本的bash? –
...現在,你*需要擺脫'exp ='賦值中的空間,或者更好地用本地數學代替:'exp = $((i * i))' –