LinuxCommandLibrary
GitHubF-DroidGoogle Play Store

bracket

Evaluate conditional expressions in shell scripts

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-zeros1 = s2: Strings equals1 != s2: Strings not equal

NUMERIC TESTS

n1 -eq n2: Equaln1 -ne n2: Not equaln1 -lt n2: Less thann1 -le n2: Less or equaln1 -gt n2: Greater thann1 -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.

HISTORY

[ (test) is one of the original Unix commands, specified in POSIX.1. The [[ enhanced version was introduced in ksh88 and adopted by bash and zsh.

SEE ALSO

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

Copied to clipboard
Kai