2013-05-10 71 views
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 

如何製作循環變量整數?謝謝。

+0

另外,你應該使用'read sni',因爲你*不需要在那裏插入可變插值。 – jpaugh 2013-05-10 22:35:22

+1

@jpaugh廣告1)可悲的是,你不能。如果你想在這裏使用變量,你必須使用'seq'(無論如何都使用'bash')。 – 2013-05-10 22:39:36

+0

哎唷!哇!你是對的。 – jpaugh 2013-05-10 22:42:04

回答

1

OK,總結了各種輸入的情況下,你要堅持你的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 
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
#!/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