0
#!/bin/sh
if [ $1+$2 -eq 1 ]
then : ;
else echo {$1..$2}
fi

Hello guys, got this code, it should do: write numbers from arg1 to arg2 ($1=3,$2=6 then 3 4 5 6 should be output)and if args are 0 and 1 or 0 and 1 it should do nothing but actually got error and bad output :

./kek1.sh: 2: [: Illegal number: 1+2
{1..2}

anyone know whats wrong?

Thank you.

Miso
  • 3
  • 1
  • Possible duplicate of [How do I iterate over a range of numbers defined by variables in bash?](http://stackoverflow.com/questions/169511/how-do-i-iterate-over-a-range-of-numbers-defined-by-variables-in-bash) – l0b0 Oct 31 '15 at 15:50

1 Answers1

0

There are several problems here:

  • Math must be performed inside an arithmetic expression $(( ... ))
  • {...} is not supported by /bin/sh.
  • Not actually a problem, but you can negate the if condition and avoid the else clause altogether.

A correct solution is

if ! [ $(( $1 + $2 )) -eq 1 ]; then
    printf "$1"
    i=$1
    while [ "$i" -lt "$2" ]; do
        i=$((i+1))
        printf " %d" "$i"
    done
fi

If available, you can use the seq command instead of the while loop:

if ! [ $(( $1 + $2 )) -eq 1 ]; then
    seq "$1" "$2"
fi
chepner
  • 497,756
  • 71
  • 530
  • 681