This is my script:
echo "please enter any number"
read n
a= $(($n % 2))
if [ $a -eq 0 ]; then
echo "EVEN"
else
echo "ODD"
fi
This is the script's output:
$ source first.sh
please enter any number
2
0: command not found
ODD
It's like what ever value I give only the else part is gets executed.
What could be the reason of the error here?
2 Answers
The problem is the space after a=. The variable assignment should be a=$(($n % 2)).
In general, spaces are important in Bash scripting. As stated in cas's answer in this relevant Unix & Linux question (which I think is worth checking out):
Things not separated by whitespace are considered to be one "word".
Things separated by one-or-more whitespace characters are considered to be two (or more) words.
This has the interesting implication that if the variable assignment is written as a=$(($n % 2)), the value right next to =, i.e. $(($n % 2)), gets assigned to a, as expected.
However, if the variable assignment is written as a= $(($n % 2)) the value right next to the = is just an empty space, which will be assigned to a. Bash will treat a as an environment variable with the value of an empty string and then proceed to evaluate $(($n % 2)), which, depending on the value of n, will be either 0 or 1. That's why you'll get the error 0: command not found or 1: command not found, depending on the case.
After that, the script will continue to the if-else statement. The expression [ $a -eq 0 ] always returns the following error (not shown in your question), due to the value of a being an empty string:
[: -eq: unary operator expected
So, finally, the else part will always get executed, thus your script will always return ODD.
Bash has its own helpful options to determine what's happening. the -v echos each line as read, and the -x prints out the line executed (after variable substitution, etc.)
$ bash -vx first.sh
bash -vx first.sh
echo "please enter any number"
+ echo 'please enter any number'
please enter any number
read n
+ read n
4
a= $(($n % 2))
+ a= <======As a comment mentioned, a space causes problems
+ 0
first.sh: line 3: 0: command not found
if [ $a -eq 0 ]; then
echo "EVEN"
else
echo "ODD"
fi
+ '[' -eq 0 ']'
first.sh: line 4: [: -eq: unary operator expected
+ echo ODD
ODD