0

Here is my script code to find when user enters n numbers to find whether numbers are odd or even, but I guess my arrays are not working

#!/bin/sh
echo "Enter the value of n:"
read n
e=0
o=0
while [ $n -gt 0 ]
do
    echo "Enter the number:"
    read a
    t=`expr $a % 2`
    if [ $t -eq 0 ]
    then
        even[e]=$a
        e=`expr $e + 1`
    else
        odd[o]=$a
        o=`expr $o + 1`
    fi
    n=`expr $n - 1`
done
echo "The even numbers are ${even[*]}"
echo "The odd numbers are ${odd[*]}"
exit 0

I get errors like

test.sh: 15: test.sh: odd[o]=1: not found
test.sh: 12: test.sh: even[e]=2: not found
test.sh: 20: test.sh: Bad substitution

Where is the error and why does it happen?

2

You are running your script with /bin/sh which simply does not have support for arrays. The bash shell, on the other hand, has.

You are also using some somewhat antiquated constructs, such as expr for doing arithmetics.

Here's a version of the script written for bash:

#!/bin/bash

read -p 'Enter n: ' n

while (( n > 0 ))
do
    read -p 'Enter number: ' a

    if (( a % 2 == 0 ))
    then
        even+=( "$a" )
    else
        odd+=( "$a" )
    fi
    n=$(( n - 1 ))
done

echo "The even numbers are ${even[*]}"
echo "The odd numbers are ${odd[*]}"

The major changes include fixing the #! line to point to bash, using (( ... )) for arithmetic evaluation, $(( ... )) for arithmetic substitution, read -p to give the user a prompt, +=(...) to add an element to an array, and removal of unneeded variables.


A non-interactive version of the script which takes the numbers from the command line:

#!/bin/bash

for number do
    if (( number % 2 == 0 )); then
        even+=( "$number" )
    else
        odd+=( "$number" )
    fi
done

printf 'The even numbers: %s\n' "${even[*]}"
printf 'The odd numbers: %s\n'  "${odd[*]}"

Testing:

$ bash script.sh 1 2 3 4
The even numbers: 2 4
The odd numbers: 1 3
  • Gives error: test.sh: 8: test.sh: Syntax error: word unexpected (expecting ")") – Sujit Maiti Oct 27 '18 at 11:55
  • @SujitMaiti This is because you are still executing the script with sh (which may be the dash shell on your machine). Either run the script with bash script.sh or make sure that the script has a proper #!-line pointing to bash on your system and that it's executable, then run it as ./script.sh. – Kusalananda Oct 27 '18 at 12:00
  • Yes, the problem is solved now! I ran the script using bash test.sh and it worked :) – Sujit Maiti Oct 27 '18 at 12:02

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.