Versions Compared

Key

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

...

Some languages (Python, Java, R) automatically detect certain types of errors (e.g. file not found) and, by default, stop program execution and may report an execution stack trace that can be displayed to the user. While these stack traces are not usually meaningful on their own, they are better than nothing, and certainly better than allowing the program to blithely continue.

...

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
}

See https://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html for conditional expressions, and https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html for conditional constructs such as if or case.

exercise 1

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

...