Griff
Griff

Reputation: 2124

make user input loop variables in shell script

I have the following script which is run as:

>> bash test.sh < 0 0

Inside test.sh

read $sni
read $snf

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

done

But I get the following error:

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

How to I make the loop variable integers? Thanks.

Upvotes: 0

Views: 3303

Answers (3)

Zombo
Zombo

Reputation: 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

Upvotes: 1

Adrian Fr&#252;hwirth
Adrian Fr&#252;hwirth

Reputation: 45576

OK, to sum up the various input and in case you want to stick with your for syntax.

read $sni

This is indirection. You are not reading into the variable ${sni} but into the variable whose name is held by ${sni}, e.g.:

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

So this should be

read sni

instead. And about ...

for i in {sni..snf}

... this does not work because you are not treating your variables as variables here. If you use ksh then you can do

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

but bash is not so clever in which case you want to use

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

So the whole thing should look more like:

#!/bin/sh

read sni
read snf

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

Example:

$ printf "1\n4\n" | ./t.sh
Run between '1' and '4'
i=1
i=2
i=3
i=4

Upvotes: 1

FDinoff
FDinoff

Reputation: 31429

You can use something like this

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

From the bash help

(( ... )): (( 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.

Also you can pass variables to the shell script as command arguments.

bash test.sh 1 2

The would be contained in the variables $1 and $2

Upvotes: 1

Related Questions