dinsdag 27 maart 2012

BASH scripting: if

if statement

if list1
then
list2
elif list3
then
list4
else
list5
fi

of

if list1; then list2 ; elif list3; then list4 ; else list5; fi ;


Test commando

Notatie: test expression of [ expression ]

3 soorten expressies
- file tests
- string comparisons
- numerical comparisons

File test

Option Description
-b file True if file exists and is a block special file.
-c file True if file exists and is a character special file.
-d file True if file exists and is a directory.
-e file True if file exists.
-f file True if file exists and is a regular file.
-g file True if file exists and has its SGID bit set.
-h file True if file exists and is a symbolic link.
-k file True if file exists and has its "sticky" bit set.
-p file True if file exists and is a named pipe.
-r file True if file exists and is readable.
-s file True if file exists and has a size greater than zero.
-u file True if file exists and has its SUID bit set.
-w file True if file exists and is writable.
-x file True if file exists and is executable.
-O file True if file exists and is owned by the effective user ID.

Voorbeeld
if [ -d /home/joop ] ; then echo hallo ; fi

String Comparisons options

-z string True if string has zero length.
-n string True if string has nonzero length.
string1 = string2 True if the strings are equal.
string1 != string2 True if the strings are not equal

if [ "$FRUIT" != apple ] ; then
echo "your fruit $FRUIT is not an apple."
else
echo "een appeltje."
fi


Numerical Comparison Operators

Operator Description
int1 -eq int2 True if int1 equals int2.
int1 -ne int2 True if int1 is not equal to int2.
int1 -lt int2 True if int1 is less than int2.
int1 -le int2 True if int1 is less than or equal to int2.
int1 -gt int2 True if int1 is greater than int2.
int1 -ge int2 True if int1 is greater than or equal to int2.

bijv.
if [ $? -ne 0 ] ; then
echo "An error."
exit
fi
echo "Command successful."

Compound expressions

! expr True if expr is false. The expr can be any valid test command.
expr1 -a expr2 True if both expr1 and expr2 are true.
expr1 -o expr2 True if either expr1 or expr2 is true.

voorbeeld
if [ -z "$DTHOME" ] && [ -d /usr/dt ] ; then DTHOME=/usr/dt ; fi
if [ -z "$DTHOME" -a -d /usr/dt ] ; then DTHOME=/usr/dt ; fi




if [ -n "$FRUIT_BASKET" ] ; then
==> FRUIT_BASKET is quoted. dit wordt gedaan omdat er in het geval dat Fruit_basket niet gezet is er een error optreed.
zonder quotes ==> [ -z ] : error
met quotes ==> [-z "" ] : geen error

Geen opmerkingen:

Een reactie posten