Scripts with conditionals

Learning outcomes:

  • Write and test a script with a conditional and explain the use of conditionals
  • Demonstrate how to debug a script with conditionals

Would you like to download my PowerPoint to follow along?

  • Basic If-Then-Else loop
    • Conditionals mean you have choices in a path, this is not the same as a loop
    •  
                          if [condition]
                          then
                          echo 
                          yes
                          
                          else
                          echo "no"
                          
                          fi 
    • if [ $answer = “Y” ] Brackets do test (can also use function test)
    • There are some required pieces of syntax such as "then" that are needed for an if statement
    • echo “Yes” If condition is true (can be multiple statements)
    • echo “No” If condition is false (can be multiple statements)
    • fi End of conditional (if backwards) is used to indicate the if statement has ended
    • if statements can also be nested if you wish to have multiple paths, be careful though! A nested if is NOT the same as two if statements next to each other.
    • if statements in bash in more detail with some examples
  • Case Statements
    • Another kind of conditional. This is still a way of indicating paths and choices, not loops, but has differnt syntax.
    • If statements can be used to evaluate if one thing has happened, or if you include if-then-else two choices, but they can also include multiple choices by using the if-elseif-elseif...-else
    • Case statement example in bash with a comparison to if-else statements
  • Conditional statement options
  • Debugging and common mistakes
    • Space matters (there and not there, can be picky)
    • Make sure the condition is right type (-eq vs = vs -f)
    • Watch for closing fi
    • Some troubleshooting tips

Suggested Activities and Discussion Topics:

  • Watch This Video on conditionals with scripting and follow along
  • Activity: Listen to This Podcast That was created using AI from these materials. Transcript for the Podcast What are your thoughts? Did the AI do a good job representing the materials? Did you find any mistakes?
  • Go through This AI generated study guide, what do you think? Did it capture the week materials well? How did you do on the self quiz? Do you know all the vocab used?
  • Go through This AI generated briefing document, what do you think? Did it capture the week materials well? Was there anything it missed? Do you know all the vocab used?

Would you like to see some more classes? Click here