Table of Contents

BASH - Tests - Exit if file is not there

Exit if file is not there

[[ -f /var/log/apt/history.log ]] || exit 1

NOTE: Just using exit should be enough, as it returns the status value of previous command (exit equals to exit $?).


Exit if path does not exist

cd /some/path || exit 1

NOTE: Will exit if path does not exist.


Or do it on a more global level with

set -e # script will from now on exit on 1st error

NOTE: The set -e option instructs bash to immediately exit if any command has a non-zero exit status.

  • Usually this command should not be set in a command-line shell, but in a script it is massively helpful.

Do not continue if the directory does not exist

config="$HOME/bin/singularity.cfg"
test -f "$config" && source "$config" >/dev/null || { echo "$config does not exist" ; exit 1; }

Do something if directory is there

[[ -d $HOME/apps/blender ]] && mv "$HOME/apps/blender" "$HOME/apps/blender_bak_$RANDOM"

With if

file="$HOME/.pcalc.txt"
if [ -f "$file" ]; then
    tail -n 100 "$file" > "$file.tmp" && mv "$file.tmp" "$file"
fi

NOTE: -e would be any file/dir/socket/node, -d is directory, and so on.

-b filename - Block special file
-c filename - Special character file
-d directoryname - Check for directory Existence
-e filename - Check for file existence, regardless of type (node, directory, socket, etc.)
-f filename - Check for regular file existence not a directory
-G filename - Check if file exists and is owned by effective group ID
-G filename set-group-id - True if file exists and is set-group-id
-k filename - Sticky bit
-L filename - Symbolic link
-O filename - True if file exists and is owned by the effective user id
-r filename - Check if file is a readable
-S filename - Check if file is socket
-s filename - Check if file is nonzero size
-u filename - Check if file set-user-id bit is set
-w filename - Check if file is writable
-x filename - Check if file is executable