computing‎ > ‎

Bash programming

Conditional operators

^  operator  ^  produces true if...  ^  no. of operands  ^
|  -n  | operand has non zero length |  1  |
|  -z  | operand has zero length     |  1  |
|  -d  | there exists a directory whose name is operand |  1  |
|  -f  | there exists a file whose name is operand |  1  |
|  -eq  | the operands are integers and they are equal |  2  |
|  -neq  | the opposite of -eq |  2  |
|  =  | the operands are equal (as strings) |  2  |
|  !=  | opposite of = |  2  |
|  -lt  | operand1 is strictly less than operand2 (both operands should be integers) |  2  |
|  -gt  | operand1 is strictly greater than operand2 (both operands should be integers) |  2  |
|  -ge  | operand1 is greater than or equal to operand2 (both operands should be integers) |  2  |
|  -le  | operand1 is less than or equal to operand2 (both operands should be integers) |  2  |

For loops

A loop over integers:

for ((i=1;i<=10;i+=1)); do
echo $i
done

While loops

myvar=0
while [ $myvar -le 10 ]
do
    echo $myvar
    myvar=$(( $myvar + 1 ))
done