Why am I getting

./6_sum_square_difference.sh: 11: ./6_sum_square_difference.sh: Illegal number: {1..3}


summing () {
  for one_num in {1..$num_in}
    printf "aaaa\n"
    the_total=$((the_total+one_num)) # <-- Line 11
summing 3
if [[ $the_total == 6 ]]; then
  echo "equa to 6 "$the_total
  echo "NOT equal to 6"
printf "total= "$the_total
  • 2
    Maybe re-read the answers/links to your question here ? – don_crissti Jan 24 '15 at 2:23
  • You forgot the z before sh in your shebang, that is why it doesn't work. – casey Jan 24 '15 at 2:31

{1..$num_in} is a kshism/zshism. You should write:

`seq $num_in`

Note: Though bash supports code like {1..3}, as said by 1_CR in comment, {1..$num_in} doesn't work in bash, due to the fact that brace expansion precedes parameter substitution. So, it probably comes from ksh93 or zsh, where it works because parameter expansion is done first.

  • 2
    actually {1..$num_in} won't work under bash either, due to the fact that brace expansion precedes parameter substitution – iruvar Jan 24 '15 at 2:19
  • 1
    @1_CR Thanks. So, that's a zshism. I've edited my answer. – vinc17 Jan 24 '15 at 2:28
  • +1, sigh, somebody should have told me about zsh before I went to all the trouble of learning bash. It's one cool shell – iruvar Jan 24 '15 at 2:31

Because {1..$num_in} did not expanded to sequences of numbers, it's only expanded to literal string like {1..1}, {1..2} and so on. So, your script performed arithmetic expansion, it saw an invalid number, and print error message.

When you use your shebang as #!/bin/sh, it depends on system to use what shell /bin/sh linked to for running your script. Thus, the error message can be varied depending on the shells.

With dash:

$ dash test.sh 
test.sh: 74: test.sh: Illegal number: {1..3}

With bash:

$ bash test.sh 
test.sh: line 74: {1..3}: syntax error: operand expected (error token is "{1..3}")
NOT equal to 6
total= 0

With pdksh and mksh:

$ pdksh test.sh 
test.sh[77]: {1..3}: unexpected '{'
NOT equal to 6
total= 0

With yash:

$ yash test.sh 
yash: arithmetic: `{1..3}' is not a valid number

posh even through a segmentation fault:

$ posh test.sh 
test.sh:77: {1..3}: unexpected `{'
Segmentation fault

The script will work with zsh and ksh93:

$ zsh test.sh 
equa to 6 6
total= 6

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.