if and test
Basic if
Commands succeed with exit status 0. if runs the then-branch on success.
if grep -q pattern file.txt; then
echo "found"
else
echo "missing"
fi
Prefer [[ ]]
Bash [[ ]] is safer and richer than old [ ] / test for scripts.
if [[ -z "${name:-}" ]]; then
echo "name required" >&2
exit 1
fi
Useful tests
-fregular file-ddirectory-eexists-r/-w/-xpermissions==/!=string compare-gt/-ltnumeric compare
Combine conditions
Use && and || inside [[ ]].
if [[ -f "$file" && -r "$file" ]]; then
cat "$file"
fi
Comments
One comment per signed-in account. Comments are saved with this page’s URL.