...
Code Block | ||
---|---|---|
| ||
# 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.
...