Bash
example of condition:
if [[ -z $1 ]]
then
echo "First argument is empty"
elif [[ -n $1 ]]
then
echo "Second argument is not empty"
else
echo "unreachable statement"
fi
File related conditions:
-e <path>- file exists-f <path>- is file-d <path>- is directory-s <path>- filesize greater than 0-x <path>- file is executable
Example of case construction:
case $1 in
0) echo "No students";;
1) echo "1 student";;
[2-4]) echo "$1 students";;
*) echo "A lot of students";;
esac
Example of while loop:
#!/usr/bin/bash
while true
do
echo "enter your name:"
read name
if [[ -z $name ]]
then
echo "bye"
break
fi
echo "enter your age:"
read age
if [[ $age -eq 0 ]]
then
echo "bye"
break
fi
group="adult"
if [[ $age -le 16 ]]
then
group="child"
elif [[ $age -le 25 ]]
then
group="youth"
fi
echo "$name, your group is $group"
done
Example of for loop:
#!/usr/bin/bash
for i in 1 2 3 4
do
echo $i
done
Another example with case and arithmetic operations:
#!/usr/bin/bash
while [ true ]
do
read left operator right
if [ $left == "exit" ]
then
echo "bye"
exit 0
fi
if [ -z $right ]
then
echo "error"
exit 0
fi
case "$operator" in
"+"|"-"|"*"|"**"|"/"|"%") let a="$left$operator$right"; echo $a;;
*) echo "error1"; exit 0;;
esac
done
Example of function:
#!/usr/bin/bash
while [ true ]
do
read n1 n2
if [ -z $n1 ]
then
echo "bye"
break
fi
gcd() {
remainder=1
if [ $n2 -eq 0 ]
then
echo "bye"
break
fi
while [ $remainder -ne 0 ]
do
remainder=$((n1%n2))
n1=$n2
n2=$remainder
done
}
gcd $1 $2
echo "GCD is $n1"
done