SD 212 Spring 2024 / Homeworks


hw12: Exit status and bash if statement

  • Due before the beginning of class on Monday, February 5

There are two tasks for today’s homework: signing up for the info challenge, and doing a new reading to help lead into our next unit,

There is no markdown file to submit — just do it!

Info Challenge

We are expecting everyone to participate in the Info Challenge in a few weeks. It is an important part of the class and we know you will get a lot out of it.

You should have received a link to this form in an email from Dr. Taylor earlier this week. Go ahead and fill that out now.

Then submit this Google form for SD212 to confirm for your instructor that you are participating and to indicate your teammate preferences.

Reading

The Linux Command Line Chapter 27: Branching with If.

Read (at least) the first two sections on if statements and exit status.

(The rest of the chapter is about the test command in bash, which is interesting and useful but not something we will expect you to be familiar with for this class.)

Questions

After doing the reading, try out these questions to check your comprehension.

  1. What do you put at the end of an if/elif/else block in bash?

    1. end
    2. endif
    3. done
    4. fi
    5. esle
    6. ;
Click to show the answer
  1. fi. It’s “if” spelled backwards!
  1. What special bash variable holds the exit status of the previous command?

    1. $?
    2. $$
    3. $exit
    4. $status
    5. None of the above
Click to show the answer
  1. $?
  1. The grep command has an exit status of 0 when it finds at least one match, and an exit status of 1 when it doesn’t find any match.

    Consider the following short bash script.

    if grep -E -m1 '^410-293-[0-9]{4}$' info.txt
    then
      : # colon in bash means do nothing
    else
      echo '410-293-5001'
    fi

    What does this program do?

Click to show the answer
Display the first USNA phone number in info.txt, or the Bancroft main office number if none is found in the file