Geavanceerd
Zoeken inSamenvattingen
Zo zoek je
  • Woorden vinden lestitels, tekst en code. Filter op soort (gidsen, cursussen, programma's, boeken) of blijf in dit boek.
  • book:rhcsa en ch:8 maken de zoektocht kleiner; #code vindt een woord alleen in commando's van de lessen.
  • "twee woorden" vindt precies die zin.
  • Gewone woorden vinden namen, teksten en voorbeelden.
  • ↑ ↓ bewegen · Enter openen · Esc sluiten · / zoeken
Probeer:

Hoofdstuk 27Naam in het boek: Flow Control: Branching with if

Make decisions with if

A script must react: is the file there, is the user root, is the number big enough? if runs commands only when a condition is true. This chapter explains exit status, test and [ ], the modern [[ ]] and (( )), how to combine conditions, and the short forms && and ||.

  • 11 Lessen
  • 6 Commando's
  • 1 Labs

Dit deel is nog niet vertaald. Je ziet de Engelse tekst.

$ als gewone gebruiker# als root (of met sudo)

Vaardigheden in dit hoofdstuk

  • Beslissingen nemen met if, test, [[ ]] en (( ))

27.1

Write an if statement

if runs a command. If the command succeeds (exit status 0), the then part runs; otherwise the else part.

the form
if commands; then
    commands
elif commands; then
    commands
else
    commands
fi
x=5
if [ "$x" -eq 5 ]; then echo "x equals 5."; else echo "x does not equal 5."; fi
x equals 5.

27.2

Understand the exit status

Every command ends with an exit status from 0 to 255. 0 means success; any other number means an error. $? holds the last status.

ls -d /usr/bin
/usr/bin
echo $?
0
ls -d /bin/usr
ls: cannot access '/bin/usr': No such file or directory
echo $?
2
true; echo $?
0
false; echo $?
1
  • Scripts and functions set their status with exit n and return n.
  • if checks the status of the last command in its condition list.

27.3

Test files

test expression or [ expression ] checks something and returns 0 (true) or 1 (false). Spaces around [ and ] are required.

ExpressionTrue if the file …
-e fileexists
-f fileexists and is a regular file
-d fileexists and is a directory
-L fileis a symbolic link
-r / -w / -x fileis readable / writable / executable for you
-s fileexists and is not empty
-O fileis owned by you
file1 -nt file2is newer than file2
file1 -ot file2is older than file2
file1 -ef file2is the same file (hard link)
test-file
#!/bin/bash
 
# test-file: evaluate the status of a file
 
FILE=~/.bashrc
 
if [ -e "$FILE" ]; then
    if [ -f "$FILE" ]; then
        echo "$FILE is a regular file."
    fi
    if [ -d "$FILE" ]; then
        echo "$FILE is a directory."
    fi
    if [ -r "$FILE" ]; then
        echo "$FILE is readable."
    fi
else
    echo "$FILE does not exist"
    exit 1
fi
 
exit

Onthoud

Put variables in quotes inside [ ]: [ -e "$FILE" ]. An empty variable without quotes gives a syntax error.

Commando's in deze les

27.4

Test strings

String tests check if a text is empty or equal to another text.

ExpressionTrue if
string / -n stringthe string is not empty
-z stringthe string is empty
s1 = s2 (or ==)the strings are equal
s1 != s2the strings are different
s1 > s2 / s1 < s2s1 sorts after / before s2 (escape in [ ]: \>)
test-string
#!/bin/bash
 
ANSWER=maybe
 
if [ -z "$ANSWER" ]; then
    echo "There is no answer." >&2
    exit 1
fi
 
if [ "$ANSWER" = "yes" ]; then
    echo "The answer is YES."
elif [ "$ANSWER" = "no" ]; then
    echo "The answer is NO."
elif [ "$ANSWER" = "maybe" ]; then
    echo "The answer is MAYBE."
else
    echo "The answer is UNKNOWN."
fi
  • >&2 sends the error message to stderr.

Commando's in deze les

27.5

Test integers

Numbers are compared with letter operators, not with < and >.

ExpressionTrue if
a -eq bequal
a -ne bnot equal
a -le b / a -lt bless than or equal / less than
a -ge b / a -gt bgreater than or equal / greater than
test-integer
#!/bin/bash
 
INT=-5
 
if [ -z "$INT" ]; then
    echo "INT is empty." >&2
    exit 1
fi
 
if [ "$INT" -eq 0 ]; then
    echo "INT is zero."
else
    if [ "$INT" -lt 0 ]; then
        echo "INT is negative."
    else
        echo "INT is positive."
    fi
    if [ $((INT % 2)) -eq 0 ]; then
        echo "INT is even."
    else
        echo "INT is odd."
    fi
fi

27.6

Use the modern [[ ]]

[[ ]] is bash's better test. It adds regex matching with =~ and pattern matching with ==, and it does not split words.

check that INT is a whole number
if [[ "$INT" =~ ^-?[0-9]+$ ]]; then
    echo "INT is an integer."
else
    echo "INT is not an integer." >&2
    exit 1
fi
FILE=foo.bar
if [[ $FILE == foo.* ]]; then echo "$FILE matches pattern 'foo.*'"; fi
foo.bar matches pattern 'foo.*'

27.7

Use (( )) for numbers

(( )) tests arithmetic. It is true when the result is not zero. Variables need no $, and <, >, == work normally.

test-integer with (( ))
if ((INT == 0)); then
    echo "INT is zero."
else
    if ((INT < 0)); then
        echo "INT is negative."
    else
        echo "INT is positive."
    fi
    if (( ((INT % 2)) == 0)); then
        echo "INT is even."
    else
        echo "INT is odd."
    fi
fi

27.8

Combine conditions

AND, OR and NOT join tests. The signs depend on the test form.

Operationtest / [ ][[ ]] and (( ))
AND-a&&
OR-o||
NOT!!
check a range
MIN_VAL=1
MAX_VAL=100
INT=50
 
if [[ "$INT" -ge "$MIN_VAL" && "$INT" -le "$MAX_VAL" ]]; then
    echo "$INT is within $MIN_VAL to $MAX_VAL."
fi
 
if [ ! \( "$INT" -ge "$MIN_VAL" -a "$INT" -le "$MAX_VAL" \) ]; then
    echo "$INT is outside $MIN_VAL to $MAX_VAL."
fi

Notitie

[ ] and test are POSIX and work in every shell. [[ ]] and (( )) are bash features: easier, but not portable to sh. For bash scripts, use the modern forms.

Commando's in deze les

27.9

Branch with && and ||

cmd1 && cmd2 runs cmd2 only if cmd1 succeeds. cmd1 || cmd2 runs cmd2 only if cmd1 fails.

mkdir temp && cd temp
[[ -d temp ]] || mkdir temp
[[ -d temp ]] || exit 1

27.10

Finish the report: check for root

Use if in the report script: only root may read all home directories.

report_home_space with a test
report_home_space () {
    if [[ "$(id -u)" -eq 0 ]]; then
        cat <<- _EOF_
			<h2>Home Space Utilization (All Users)</h2>
			<pre>$(du -sh /home/*)</pre>
			_EOF_
    else
        cat <<- _EOF_
			<h2>Home Space Utilization ($USER)</h2>
			<pre>$(du -sh "$HOME")</pre>
			_EOF_
    fi
    return
}

27.11

Summary of the chapter

if checks an exit status; [ ], [[ ]], (( )) make tests; && and || are short branches.

1Which exit status means success?

0.

2Which test checks that a variable is a whole number?
3What does [[ -d backup ]] || mkdir backup do?

It makes the directory backup only if it does not exist yet.

Commando's in deze les

Oefenen

Alle commando's in dit hoofdstuk