Welcome to the Linux Foundation Forum!

bash scripting question

I went back to LFS101 to touch up on scripting when I realized I needed some more work there while taking LFS201. I ran into a lab that had an answer that was more complicated than what I used, but performed the same (at least I believe it did, if not please let me know what I did wrong).

The prompt was:

Write a script which:
Asks the user for a number, which should be "1" or "2". Any other input should lead to an error report.
Sets an environmental variable to be "Yes" if it is "1", and "No" if it is "2".
Exports the environmental variable and displays it.

The script supplied as the answer:

#!/bin/bash

echo "Enter 1 or 2, to set the environmental variable EVAR to Yes or No"
read ans

 # Set up a return code
RC=0

if [ $ans -eq 1 ]  
then 
    export EVAR="Yes"
else
    if [ $ans -eq 2 ]
    then
    export EVAR="No"
    else
 # can only reach here with a bad answer
    export EVAR="Unknown"
    RC=1
    fi    
fi
echo "The value of EVAR is: $EVAR"
exit $RC

And this is what I used:

#!/bin/bash

echo "Pick 1 or 2 to set the environmental variable to Yes or No"
read answer

if [ $answer -eq 1 ]
then
    export ev="Yes"
elif [ $answer -eq 2 ]
then
        export ev="No"
else
        export ev="ERROR: please pick 1 or 2"
fi
echo "The environmental variable is: $ev"

Both of them produce the same outcome, they both assign 1 to yes, 2 to no, and print an error when anything else is used. So I have a few questions:
What is the purpose of the return code they used?
Why is the if else formatted that way if it can be done with less typing?

Thanks for any help on this

Categories

Upcoming Training