bash:tests:exit_if_file_is_not_there

This is an old revision of the document!


BASH - Tests - Exit if file is not there

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

NOTE: Will exit if file is not there, same thing should be used if you use cd in your scripts

  • Actually just using exit should be enough, as it returns the status value of previous command (exit equals to exit $?).

cd /some/path || exit 1

Or do it on a more global level with

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

This will ensure that script doesn’t continue if dir doesn’t exist. Another way might be:

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 that -e would be any file/dir/socket/node, -d is dir 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

bash/tests/exit_if_file_is_not_there.1686690992.txt.gz · Last modified: 2023/06/13 21:16 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki