LinuxCommandLibrary

bracket

TLDR

Test condition (synonym for test)

$ [ -f [file] ] && echo "exists"
copy
String comparison
$ [ "[string1]" = "[string2]" ]
copy
Numeric comparison
$ [ [5] -gt [3] ]
copy
File tests
$ [ -d [directory] ] && echo "is directory"
copy
Combine conditions
$ [ -f [file] ] && [ -r [file] ]
copy

SYNOPSIS

[ expression ]

DESCRIPTION

[ is the POSIX test command for evaluating conditional expressions. It's equivalent to test but requires a closing ]. Spaces around [ and ] are mandatory.
The command returns exit status 0 (true) or 1 (false), used in if statements and conditional execution.

$ if [ -f "$file" ]; then
    echo "File exists"
fi

[ -d "$dir" ] && cd "$dir"
copy
For bash/zsh, [[ provides an enhanced version with pattern matching and safer syntax.

FILE TESTS

-e file: File exists
-f file: Regular file
-d file: Directory
-r file: Readable
-w file: Writable
-x file: Executable
-s file: Size > 0
-L file: Symbolic link

STRING TESTS

-z string: Length is zero
-n string: Length is non-zero
s1 = s2: Strings equal
s1 != s2: Strings not equal

NUMERIC TESTS

n1 -eq n2: Equal
n1 -ne n2: Not equal
n1 -lt n2: Less than
n1 -le n2: Less or equal
n1 -gt n2: Greater than
n1 -ge n2: Greater or equal

CAVEATS

[ is a command, not syntax. Spaces are required: [ "$a" = "$b" ] not ["$a"="$b"].
Always quote variables: [ "$var" = "test" ] to handle empty values and spaces.
Use -a and -o for AND/OR, or combine with && and || outside brackets.
= is for strings, -eq for numbers: [ "01" = "1" ] is false, [ 01 -eq 1 ] is true.

SEE ALSO

test(1), bash(1), sh(1)

Copied to clipboard