我有以下脚本:
>> 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
如何使循环变量整数?感谢。
答案 0 :(得分: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
答案 1 :(得分: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
答案 2 :(得分: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