Dit deel is nog niet vertaald. Je ziet de Engelse tekst.
Wat het doet
test EXPRESSION and [ EXPRESSION ] are the same; the ] is required and needs spaces around it. They are used with if, while, && and ||. Bash also has [[ … ]], which adds pattern matching (== with *), regular expressions (=~) and safer handling of empty variables.
Zo schrijf je het
test EXPRESSION
[ EXPRESSION ]
[[ EXPRESSION ]]Belangrijkste delen
Files
-eFILE- Exists (any type).
-fFILE- Is a regular file.
-dFILE- Is a folder.
-LFILE,-hFILE- Is a symbolic link.
-bFILE,-cFILE- Block / character device.
-pFILE,-SFILE- Named pipe / socket.
-sFILE- Exists and is not empty.
-rFILE,-wFILE,-xFILE- Readable / writable / executable for you.
-uFILE,-gFILE,-kFILE- SUID / SGID / sticky bit set.
-OFILE,-GFILE- Owned by you / by your group.
-NFILE- Changed since last read.
FILE1-ntFILE2,FILE1-otFILE2- Newer / older than.
FILE1-efFILE2- Same file (hard link).
Strings
-zSTRING- Empty.
-nSTRING- Not empty.
S1=S2,S1!=S2- Equal / not equal.
S1S2, S1S2- Sort order (escape in [ ]:
\<). S=~REGEX- Matches a regular expression (only [[ ]]).
Numbers
N1-eqN2,-ne- Equal / not equal.
N1-ltN2,-le- Less / less or equal.
N1-gtN2,-ge- Greater / greater or equal.
Logic
!EXPR- Not.
EXPR1-aEXPR2,EXPR1-oEXPR2- And / or (old; better:
[ A ] && [ B ]). &&,||- And / or inside [[ ]].
-vNAME- The variable is set (bash).
Voorbeelden 11
$ als gewone gebruiker# als root (of met sudo)
1Does a file exist?
[ -f /etc/fstab ] && echo "yes" yesSpaces inside the brackets are required.
2In an if
-d = folder.
3Compare strings
[ "$USER" = "root" ] || echo "run as root"Quote variables: empty values break
[ = root ].4Compare numbers
-gt for numbers, not >.
5Check the number of arguments
Common at the start of scripts.
6Empty variable
NAME=""; [ -z "$NAME" ] && echo "empty"-n for not empty.
7Pattern match with [[ ]]
FILE=report.csv; [[ $FILE == *.csv ]] && echo "CSV file"Wildcards work only in [[ ]].
8Regular expression
IP=192.168.122.10; [[ $IP =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]] && echo "looks like an IPv4"=~ in [[ ]].
9Find world-writable scripts (security)
for f in /usr/local/bin/*; do [ -w "$f" ] && [ "$(stat -c %a "$f" | cut -c3)" -ge 2 ] && echo "$f is world-writable"; doneAnybody could change these scripts.
10Is a file newer than another?
[ /etc/nginx/nginx.conf -nt /var/run/nginx.pid ] && echo "config changed since start"Reload needed.
11Exit status of test
test 5 -gt 3; echo $? 00 = true, 1 = false.
Niets past bij dit filter.
Let op
[ $VAR = x ]fails when VAR is empty; write[ "$VAR" = x ].>inside [ ] is a redirect, not a compare. Use -gt for numbers.
Exitcodes
0 :: The expression is true. 1 :: The expression is false. 2 :: Error in the expression.