0

I have to hand write responses to a script that is already given to me. The two sets of information I have to give an output for are if the variables that will be read are 3 3 3, and 20 3 5.

I decided to test the script first, but keep having syntax errors on line 19, and can't figure out what the issue is. I have tested multiple variants of the spacing and parenthesis, but can't quite get there. Any help would be appreciated.

#!/bin/sh
## Name of the program is challengelab3.2

## request information from the user
echo enter 3 numbers
read a b c

## check for proper range of numbers
if [ $a -gt 10 -o $b -gt 10 -o $c -gt 5 ]; then
    echo "numbers out of range"
    exit 1
fi

# process_data
x=$(($a + $b + $c))

while [ $x -gt 0 ]
do
     echo (( $x / 2%2 ))
     x=$((expr $x -1))
done

# end of program
  • 1
    x=$((expr $x -1)) should either be arithmetic ((x--)) or command substitution with single parentheses x=$(expr $x -1) -- however sh does not have arithmetic expressions built-in, so either use bash or ksh, or stick to expr everywhere – glenn jackman Nov 29 '15 at 12:20
1

Try this instead:

#!/bin/sh
## Name of the program is challengelab3.2

## request information from the user
echo enter 3 numbers
read a b c

[ -z "$a" ] && echo a is missing, enter all 3 numbers && exit 1
[ -z "$b" ] && echo b is missing, enter all 3 numbers && exit 1
[ -z "$c" ] && echo c is missing, enter all 3 numbers && exit 1

if [ "$a" -gt 10 -o "$b" -gt 10 -o "$c" -gt 5 ]; then
    echo "numbers out of range"
    exit 1
fi

# process_data
x=$((a + b + c))

while [ "$x" -gt 0 ]
do
    echo $(( x / 2 % 2 ))
    x=$((x - 1))
done
  1. shell arithmetic is done with $(( ... ))

  2. Remember to quote your variables outside of $(()) and [[ ]]. Without the quotes, if $a or $b or $c are undefined (e.g. user enters only 1 or 2 numbers) there will be a syntax error because -gt requires two operands.

  • The -o syntax is perfectly valid, it will throw errors if $a $b or $ are non-numeric or blank, as will your code. - this comment refers to your answer before it was completely changed(!) – gogoud Nov 29 '15 at 5:58
  • line 20: expr 9 -1: syntax error in expression (error token is "9 -1") is what I am getting from the changes you have posted so far – Mister123 Nov 29 '15 at 6:05
  • Very good cas +1! Jake26x, you could debug your bash code with #!/bin/sh -xv to get more help. – Facundo Victor Nov 29 '15 at 6:10
  • My final output from the given code corrections using variables 3 3 3 for read was 3 3 3 (on one line) 0 0 1 1 0 0 1 1 0 – Mister123 Nov 29 '15 at 6:12

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.