if and test

View saved

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

  • -f regular file
  • -d directory
  • -e exists
  • -r/-w/-x permissions
  • == / != string compare
  • -gt / -lt numeric 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.