1

Why am I getting

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

for

#!/bin/sh
summing () {
  the_total=0
  num_in=$1
  for one_num in {1..$num_in}
  do  
    printf "aaaa\n"
    the_total=$((the_total+one_num)) # <-- Line 11
  done
}
summing 3
if [[ $the_total == 6 ]]; then
  echo "equa to 6 "$the_total
else
  echo "NOT equal to 6"
fi
printf "total= "$the_total

2 Answers2

3

{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.

vinc17
  • 12,174
  • 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 02:19
  • 1
    @1_CR Thanks. So, that's a zshism. I've edited my answer. – vinc17 Jan 24 '15 at 02: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 02:31
1

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 
aaaa
test.sh: 74: test.sh: Illegal number: {1..3}

With bash:

$ bash test.sh 
aaaa
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 
aaaa
test.sh[77]: {1..3}: unexpected '{'
NOT equal to 6
total= 0

With yash:

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

posh even through a segmentation fault:

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

The script will work with zsh and ksh93:

$ zsh test.sh 
aaaa
aaaa
aaaa
equa to 6 6
total= 6
cuonglm
  • 153,898