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:

  1. #!/bin/bash
  2.  
  3. echo "Enter 1 or 2, to set the environmental variable EVAR to Yes or No"
  4. read ans
  5.  
  6. # Set up a return code
  7. RC=0
  8.  
  9. if [ $ans -eq 1 ]
  10. then
  11. export EVAR="Yes"
  12. else
  13. if [ $ans -eq 2 ]
  14. then
  15. export EVAR="No"
  16. else
  17. # can only reach here with a bad answer
  18. export EVAR="Unknown"
  19. RC=1
  20. fi
  21. fi
  22. echo "The value of EVAR is: $EVAR"
  23. exit $RC

And this is what I used:

  1. #!/bin/bash
  2.  
  3. echo "Pick 1 or 2 to set the environmental variable to Yes or No"
  4. read answer
  5.  
  6. if [ $answer -eq 1 ]
  7. then
  8. export ev="Yes"
  9. elif [ $answer -eq 2 ]
  10. then
  11. export ev="No"
  12. else
  13. export ev="ERROR: please pick 1 or 2"
  14. fi
  15. 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

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

Categories

Upcoming Training