1

I am trying to loop from 1 to n where n is from user input. If I do:

read n
echo {1..$n}

I get this output for the input 5

{1..5}

How do I make it expand to

1 2 3 4 5
  • You *cannot* use variables within brace-expansion. (not without the cludge of `eval` -- don't do it, use a proper loop, or `seq` or the like) Since this is base, just use a C-style `for` loop, e.g. `for ((i = 1; i <= n; i++)); do...` – David C. Rankin May 20 '18 at 05:33
  • I suggest to use a function: `echo $(c 1 $n)`. `echo` can be omitted here. – Cyrus May 20 '18 at 06:28

1 Answers1

1

Keep it simple by trying to do it with a for loop as follows.

echo "enter number..."
read n

for((i=1;i<=n;i++)); do
        echo "$i"
done

Or use seq with for loop as follows too.

echo "Enter number:"
read howmany
for i in $(seq 1 $howmany); do
  echo "$i";
done

Curly braces don't support variables in bash, though eval could be used but it is evil and have loopholes, why so see this link carefully http://mywiki.wooledge.org/BashFAQ/048

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • You have a good answer, but I have more explanation in a comment -- try adding a bit of explanation so the user knows why what he is doing is wrong `:)` – David C. Rankin May 20 '18 at 05:36
  • @DavidC.Rankin, oh sorry looks like 1 min difference only, let me add some more comments to it now too. – RavinderSingh13 May 20 '18 at 05:37
  • 1
    Good deal -- remember - you step into the role of 'teacher' when answering. We all remember to good ones, and the ones we love to hate... (you may want to even explain why the `'$'` isn't needed to dereference variables with `((...))`, just so he (or she) isn't scratching their head) – David C. Rankin May 20 '18 at 05:38
  • @DavidC.Rankin, sure, I tried to find on SO and got to know why eval is evil so added a link with a line of explanation too sir, please feel free to edit it in case you think we could add something to it too. – RavinderSingh13 May 20 '18 at 06:06