Many of the answers are correct but I feel like they could be more complete
/ simplistic etc. for example :
Example 1 : Basic if statement
# BASH4+ example on Linux :
typeset read_file="/tmp/some-file.txt"
if [ ! -s "${read_file}" ] || [ ! -f "${read_file}" ] ;then
echo "Error: file (${read_file}) not found.. "
exit 7
fi
if $read_file is empty or not there stop the show with exit. More than once I have had misread the top answer here to mean the opposite.
Example 2 : As a function
# -- Check if file is missing /or empty --
# Globals: None
# Arguments: file name
# Returns: Bool
# --
is_file_empty_or_missing() {
[[ ! -f "${1}" || ! -s "${1}" ]] && return 0 || return 1
}
diff
call, just check the return value:if diff foo.txt bar.txt; then echo 'No difference'
– Maggotyif [ ! -s diff.txt ]; then echo "IS EMPTY";else echo "HAS SOMETHING";fi
– Kenyettakenyon$ cat diff.txt | hexdump -C
– Venereal[ … ]
is different from bash’s native[[ … ]]
, in that the latter allows some things that would break the former. E.g. w.r.t. quoting or comparison operators. – Sonnysonobuoy