Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The check_res function checks the result/exit code passed in to it (usually our friend $?). Note that here and in other error checking fuctions, maybe_echo is used for diagnostic messages, so that they can be suppressed via the ECHO_VERBOSE environment variable.

Code Block
languagebash
# Function to check result code of programs.
# Exits with a standard error message if code is non-zero.
# Otherwise displays a completion message.
#   arg 1 - the return code (usually $?)
#   arg 2 - text describing what ran (optional)
check_res() {
  if [[ "$1" == "0" ]]; then maybe_echo ".. check_res: $2 OK";
  else err "$2 returned non-0 exit code $1"; fi
}

...

Code Block
languagebash
# Function that checks if a directory exists and exits if not.
#   arg 1 - the directory name
#   arg 2 - text describing the directory (optional)
check_dir() {
  if [[ ! -d "$1" ]]; then err "$2 Directory '$1' not found"
  else maybe_echo ".. $2 directory '$1' exists"; fi
}
# Function that checks if a file exists
#   arg 1 - the file name
#   arg 2 - text describing the file (optional)
check_file() {
  if [[ ! -e "$1" ]]; then err "$2 File '$1' not found"
  else maybe_echo ".. $2 file '$1' exists"; fi
}
# Function checks if a file exists & has non-0 length, else exits.
#   arg 1 - the file name
#   arg 2 - text describing the file (optional)
check_file_not_empty() {
  if [[ ! -e "$1" ]]; then err "$2 File '$1' not found"
  elif [[ ! -s "$1" ]]; then err "$2 File '$1' is empty"
  else maybe_echo ".. $2 file '$1' exists and is not empty"; fi
}

exercise

...

1

Explore these file checking functions in the safety of a sub-shell.

Expand
titleSolution
Code Block
languagebash
tmux new
source step_04.sh

( check_dir ~/ )
( check_dir ~/ 'my home' )
( check_file_not_empty ~/workshop/step_04.sh 'script' )
( check_file not_a_file.txt )

exit

...

Code Block
languagebash
# Checks that its 1st argument is not empty
#   arg 1 - the value
#   arg 2 - text desribing what the value is (optional)
check_arg_not_empty() {
  local val="$1"; local info=${2:-'value'}
  if [[ "$val" == "" ]]; then err "$info value is empty"
  else maybe_echo ".. $info value not empty"
  fi
}
# Function that checks whether the two values supplied are equal (as strings)
#   arg 1 - 1st value
#   arg 2 - 2nd value
#   arg 3 - text describing 1st value (optional)
#   arg 4 - text describing 2nd value (optional)
check_equal() {
  local val1="$1"; local val2="$2"
  local tag1=${3:-"val1"}; local tag2=${4:-"val2"}
  if [[ "$1" == "$2" ]]; then
    maybe_echo ".. check_equal $tag1 '$val1' OK"
  else
    echo_se "check_equal: not equal:
    ${tag1}: '$val1'
    ${tag2}: '$val2'
    "
    err "check_equal $tag1 $tag2"
  fi
}

exercise

...

2

Explore these value checking functions in the safety of a sub-shell.

...