If-then (Bash)

Uit De Vliegende Brigade
Naar navigatie springen Naar zoeken springen
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Basic example

#!/bin/bash

mijnvar=$1

if [ -z "$mijnvar" ]
then
   #
   echo "mijnvar is leeg"
   #
elif [[ "$mijnvar" =~ [0-9] ]]   # Geen idee waarom je dubbele vierkante haakjes hebt
then
   #
   echo "Mijnvar is een getal"
   #
fi

Op één regel

Een if-then-statement kan prima op één regel, vermits je de afzonderlijke commando's voorziet van een ;. Voorbeeld:

# Verify variables
#######################################
#
if [ -z "$db_name" ]; then echo "Variable 'db_name' not provided. Exiting"; exit; fi
if [ -z "$db_username" ]; then echo "Variable 'db_username' not provided. Exiting"; exit; fi
if [ -z "$db_pass" ]; then echo "Variable 'db_pass' not provided. Exiting"; exit; fi

AND

Gebruik && als de logische AND-operator:

#!/bin/bash

a=1
b=2

if [ "$a" = 1 ]; then
	echo "a=1"
fi

if [ "$a" = 1 ] && [ "$b" = 2 ]; then
	echo "a=1 en b=2"
fi

At another instance, I had to use double "[]". Don't ask me why:

if [[ "$site_cat" =~ "_bal_" ]] && [[ "$site_cat" =~ "_cb_" ]]

Non-existing variable

Je kunt straffeloos testen met een niet-bestaande variabele:

#!/bin/bash

if [ "$c" = 1 ]; then
	echo "Non-existing variable 'c' is equal to 1"
else
	echo "Non-existing variable 'c' is not equal to 1"	
fi

See also

Bronnen