(bash)

CIS241

System-Level Programming and Utilities

bash Conditionals

Erik Fredericks, frederer@gvsu.edu
Fall 2025

Based on material provided by Erin Carrier, Austin Ferguson, and Katherine Bowers

CIS241 | Fredericks | F25 | 22-bash-conditionals

if

General form:

if CONDITION
then
  # do the things
fi

or:

if CONDITION; then
  # do the things
fi
CIS241 | Fredericks | F25 | 22-bash-conditionals

CONDITION?

Think of your if tests - those are conditionals

if [ $1 -lt 10 ]; then
  # do things here
fi

What does this do?

CIS241 | Fredericks | F25 | 22-bash-conditionals

MORE

 
 
 
 
 
 
 
 
 
 
 
 

A reference: https://ryanstutorials.net/bash-scripting-tutorial/bash-if-statements.php

top-right (bash ifs)

CIS241 | Fredericks | F25 | 22-bash-conditionals

Conditions

  • Can also run man test

Alternative - arithmetic expression!

if (( $1 < 10 )); then
  # do things
fi
CIS241 | Fredericks | F25 | 22-bash-conditionals

And then, the else

if CONDITION; then
  # do thing 1
elif CONDITION2; then
  # do thing 2
else
  # do thing 3
fi
CIS241 | Fredericks | F25 | 22-bash-conditionals

Boolean operators

if [ $1 -lt 10 ] && [ $1 -gt 0 ]; then
  # do stuff
fi
	
if [ -z $2 ] || [ $2 = “start” ]; then
  # do stuff
fi
CIS241 | Fredericks | F25 | 22-bash-conditionals

And finally, the case

test1="HELLO"

case $test1 in
HELLO | HI)
  echo "case successful: $test1" ;;
ANOTHER)
  echo "a different case" ;;
"AND ANOTHER")
  echo "different yet again";;
*)
  echo "default case" ;;
esac

https://linuxize.com/post/bash-case-statement/

CIS241 | Fredericks | F25 | 22-bash-conditionals

if ! [ $a -lt 10 ]; then echo "hi"; fi if [ -e favicon.ico ] ; then echo "wee"; fi

-z is "string empty?" show math mode too if (( 1 == 1 )); then echo "hi"; fi if (( 1 == 2 )); then echo "hi"; fi if (( 1 == 1 && 2 == 2 )); then echo "hi"; fi if (( 1 == 1 && 2 == 1 )); then echo "hi"; fi if (( 1 == 1 || 2 == 1 )); then echo "hi"; fi if (( 1 == 1 || (2 == 1) )); then echo "hi"; fi if (( (1 == 1) || (2 == 1) )); then echo "hi"; fi if (( (1 == 1) && (2 == 1) )); then echo "hi"; fi