1

I would like to use the numeric value of the input argument that I pass to a bash script like this:

./script_pb3.sh out.txt 3

Here I would like to take the second argument that I pass (i.e. the value 3) and use it as a numeric value inside my script, that looks like this:

#!/bin/bash
NUM=$2

for i in {1..$NUM}; do
        echo $i
done

But when I run it all I get is

{1..3}

Instead of

1
2
3

Can you please provide an explanation for why this is happening and a workaround? I think that this question aims at casting a string value to an integer value but I am not sure. Any help is greatly appreciated.

EDIT: the answer from here contains a debate concerning the answer to my issue (i.e. it assumes the answer is already known), but it does not come as an answer to my question, therefore I didn't find it in my first searches. Thank you, though, for pointing it out.

Community
  • 1
  • 1
MihaiD
  • 63
  • 1
  • 10

1 Answers1

0

I think you have to use seq

for i in `seq 1 10`;
 do
    echo $i
 done    

Reference: http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html

So, what you're looking for is : seq 1 $2

attaboy182
  • 2,039
  • 3
  • 22
  • 28
  • This is a legit answer as well. Please edit the seq into `seq 1 $2` so I can accept your answer to my question – MihaiD May 21 '15 at 19:57
  • The page you linked to contains numerous questionable, unnecessary, and/or obsolete suggestions. In this case, `seq` is an unnecessary (and nonstandard) external requirement when `bash` itself already has a more efficient C-style loop. – chepner May 21 '15 at 20:34
  • I was just trying to give an answer which I felt was closest to the problem in hand. If you felt otherwise, please feel free to post an answer which you feel would be better – attaboy182 May 21 '15 at 23:29