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:


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

 # Set up a return code

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

And this is what I used:


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

if [ $answer -eq 1 ]
    export ev="Yes"
elif [ $answer -eq 2 ]
        export ev="No"
        export ev="ERROR: please pick 1 or 2"
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


Upcoming Training