for语句的问题(shell脚本)



我不知道我是否正确理解shell脚本中的for句。这就是我要做的

#!/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

显示:"语法错误:Bad for循环变量"

如果您将脚本设置为可执行的: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,因为它是在for开始时设置的):

#!/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 squaresn"
for ((i=1; i<=100; i++)); do
    echo "N: $i EXP: $(( i**2 ))"
done

如何运行这个脚本?

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

因为这看起来像dash错误,因为破折号不支持算术for循环语法

最新更新