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

Would you like to see some more classes? Click here