0

我有以下脚本运行为:

>> bash test.sh < 0 0

内部 test.sh

read $sni
read $snf

echo 'Run between '$sni' and '$snf
for i in {sni..snf}
do

done

但我收到以下错误:

test.sh: line 14: [: {sni..snf}: integer expression expected
test.sh: line 19: [: {sni..snf}: integer expression expected

如何使循环变量整数?谢谢。

4

3 回答 3

1

你可以使用这样的东西

for (( i=$sni ; i<=$snf ; i++ ))

来自 bash 帮助

(( ... )): (( expression ))
    Evaluate arithmetic expression.

    The EXPRESSION is evaluated according to the rules for arithmetic
    evaluation.  Equivalent to "let EXPRESSION".

    Exit Status:
    Returns 1 if EXPRESSION evaluates to 0; returns 0 otherwise.

您也可以将变量作为命令参数传递给 shell 脚本。

bash test.sh 1 2

将包含在变量$1$2

于 2013-05-10T22:25:45.480 回答
1
#!/bin/sh
if [[ ! $2 ]]
then
  echo test.sh SNI SNF
  exit
fi

echo "Run between $1 and $2"
seq $1 $2 | while read i
do
  # do stuff
done
于 2013-05-10T22:27:38.833 回答
1

好的,总结各种输入,以防你想坚持你的for语法。

read $sni

这是间接的。您不是在读入变量${sni},而是读入名称由 保存的变量${sni},例如:

$ foo=bar
$ read $foo <<< "quux"
$ echo "${foo}"
bar
$ echo "${bar}"
quux

所以这应该是

read sni

反而。而关于...

for i in {sni..snf}

...这不起作用,因为您没有在这里将变量视为变量。如果你使用ksh 那么你可以做

for i in {${sni}..${snf}}; do
    ...
done

bash在你想使用的情况下不是那么聪明

for i in $(seq ${sni} ${snf}); do
    ...
done

所以整个事情应该看起来更像:

#!/bin/sh

read sni
read snf

echo "Run between '${sni}' and '${snf}'"
for i in $(seq ${sni} ${snf}); do
        echo "i=$i"
done

例子:

$ printf "1\n4\n" | ./t.sh
Run between '1' and '4'
i=1
i=2
i=3
i=4
于 2013-05-10T22:56:18.307 回答