Bash Logic


Conditional Logic

Any commands and grammars that set exit codes can be used for conditional logic.

if grep /path/to/file --fixed-strings foo >/dev/null; then
  :
fi

The [[ builtin sets the exit code to 0 if a test evaluates to true, and 1 otherwise.

if [[ TEST ]]; then
  :
fi

The (( builtin sets the exit code to 0 if an arithmetic expression resolves to any non-zero number, and 1 otherwise. See here for details on valid arithmetic.

if (( $var - 1 )); then
  :
fi


Conditional Commands

To execute a command conditionally after another command, try:

true && echo "This only executes because the first command set an exit code of 0"

false || echo "This only executes because the first command set an exit code of 1"

These operators have equal precedence.


Case Switching Logic

case $INPUT_STRING in
  y)
    echo "Proceeding..."
    ;;
  n)
    echo "Quitting..."
    ;;
  *)
    echo "Please enter y or n only"
    ;;
esac


CategoryRicottone

Bash/Logic (last edited 2023-01-21 22:13:46 by DominicRicottone)