0

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.

5
  • Also, you should be using read sni, because you don't want variable interpolation there. Commented May 10, 2013 at 22:35
  • 1
    @jpaugh ad 1) Sadly, you can't. If you want to use variables here you have to use seq (with bash anyway). Commented May 10, 2013 at 22:39
  • Ouch! Wow! You're right. Commented May 10, 2013 at 22:42
  • @jpaugh We can pretend that you were suggesting to use ksh, which is cleverererer than bash and there it works :-) Commented May 10, 2013 at 22:44
  • Haha. Unfortunately, I wasn't that bright. :-) Commented May 10, 2013 at 22:45

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.