Test Operators in Shell

Level 4171 keystrokes

[[ ]] tests conditions such as file existence, an empty string or a regex match, and && / || run a command depending on the result. The output assumes config.txt exists and var and str are unset.

Shell code

# File name to test
1file="config.txt"
# -f: true if it is an existing regular file; && runs echo only then
2[[ -f $file ]] && echo "File exists"
# -d: true if logs is a directory; || creates it only when it is missing
3[[ -d "logs" ]] || mkdir logs
# -z: true for an empty string; an unset var counts as empty
4[[ -z "$var" ]] && echo "Variable is empty"
# =~ matches a regex: digits only; empty str does not match, so nothing is printed
5[[ "$str" =~ ^[0-9]+$ ]] && echo "Numeric"

Output

File exists
Variable is empty
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Shell code and how often they appear.

  • "× 14
  • [× 9
  • ]× 9
  • &× 6
  • -× 4
  • $× 4
  • =× 2
  • |× 2
  • .× 1
  • ^× 1

More Shell examples at level 4

← Shell typing practice