0

I am trying to use command line arguments for arithmetic but cant seem to find any documentation explaining how to do this. As an example if I use:

for i in {$1..$2}
do 
echo $i 
done 

and call

test.sh 1 20

the following output is produced:

{1..20} 

instead of

1
2
3
.. 
20 
Teererai Marange
  • 2,044
  • 4
  • 32
  • 50
  • 2
    This is bash, so a c-style for loop `for ((i = $1; i <= $2; i++)); do ...` is also an option. For POSIX shell, you can always use `i = $1; while [ "$i" -le "$2" ]; do ... ((i++)); done` as another option. – David C. Rankin Dec 10 '19 at 03:45

2 Answers2

0

There's no way to do this properly without the evil eval() with brace expansion in .

You can use seq instead :

for i in $(seq $1 $2); do
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • answering a well-known duplicate :/ – oguz ismail Dec 10 '19 at 03:49
  • 1
    I would definitely suggest a comment alone without DV is sufficient reminder... we don't need to be nickle and diming each other here. – David C. Rankin Dec 10 '19 at 03:51
  • @David How could I know you're talking to me if you don't @ me ? :D – oguz ismail Dec 10 '19 at 04:01
  • 1
    Hmmm... process of elimination? `:)` I do think among those that have been here a while, a friendly reminder instead of a ding is probably good practice. I know I've been guilty of answering a duplicate before -- especially when searching and "Related" don't disclose them immediately. In fact, a check of the entire *Related* list to the right doesn't disclose anything related (very flawed algorithm), but like you, I know one should exist. – David C. Rankin Dec 10 '19 at 04:10
  • Okay, next time I won't dv – oguz ismail Dec 10 '19 at 04:11
  • 1
    What does DV means ? – Gilles Quénot Dec 10 '19 at 04:29
0

The following will also work:

declare -a ary='({'$1..$2'})'
for i in "${ary[@]}"; do
    echo "$i"
done

Note that declare is as harmful as eval. You need to check and sanitize the arguments before use.

tshiono
  • 21,248
  • 2
  • 14
  • 22
  • Huh? I've never hear `declare` being considered harmful. For 30 years I've been under the impression it was helpful. (but certainly never as you use it above...) `eval` is only one character away from `evil`, but `declare` is innocent of any crime... – David C. Rankin Dec 10 '19 at 04:12
  • 1
    @DavidC.Rankin Thank you for the comment. We can invoke the script above with `test.sh 1 '$(rm file)'` then it removes `file` if exists. We can inject any command as an argument. That is my concern. – tshiono Dec 10 '19 at 04:19
  • Those are valid concerns. I can honestly say I've never seen `declare` abused this way before `:)`, – David C. Rankin Dec 10 '19 at 04:27
  • @DavidC.Rankin Thank you for your attention.There will be no end if we worry and need to find a practical solution depending on the usage and requirements. BR. – tshiono Dec 10 '19 at 04:48