Last time we already learn about selection and repetition using test and operator
right now we will use if,case, for,while, until and select
if
below is the example
#!/bin/bash
key="bash";
read -s -p "Your Password : " pass
if [ $pass==$kunci ]; then
echo "Success, You are able to login"
else
echo "Sorry, Your password is wrong";
fi
below is the result
[elvin@TestBed$]./if2
Password anda : bash
Success, You are able to login
[fajar@linux$]./if2
Password anda : Bash
Sorry, Your password is wrong
else will be execute if the condition is not being fulfilled
below is the example of nested if
#!/bin/bash
clear
echo "Menu of the day";
echo "---------------";
echo "1. Noodle ";
echo "2. Satay ";
echo "3. Exit ";
read -p "Your choose [1-3] :" pil;
if [ $pil -eq 1 ];
then
echo "How Many =";
read sum
let pay=sum*1500;
elif [ $pil -eq 2 ];
then
echo "How Many =";
read sum
let pay=sum*2000;
elif [ $pil -eq 3 ];
then
exit 0
else
echo "Sorry, Your choose is not available"
exit 1
fi
echo "Total Payment = Rp. $pay"
echo "THX"
below is the result
[elvin@TestBed$]./if3
Menu of the day
---------------
1. Noodle
2. Satay
3. Exit
Your choose[1-3] :2
How Many = 2
Total Payment = Rp. 4000
THX
case
the function of case is same like if. for sometimes condition, case is more efficience than if command
below is the example
#!/bin/bash
clear
echo -n "Please input your menu :";
read menu;
case $menu in
noodle | kwetiau | bihun ) echo "$menu is chinese food"
break
;;
steak | pizza | sandwich ) echo "$menu is western food"
break
;;
*) echo "$menu is not being defined"
break
;;
esac
below is the result
[elvin@TestBed$]./cs1
Please input your menu : noodle
noodle is chinese food
for
for statement is using for repetition
below is the example
#!/bin/bash
for number in 1 2 3 4 5;
do
echo "number=$number";
done
below is the result
[elvin@TestBed$]./for1
number=1
number=2
number=3
number=4
number=5
while
while statement will do the command as long as the condition is true
below is the example to print odd number
#!/bin/bash
i=1;
while [ $i -le 10 ];
do
echo "$i,";
let i=$i+2;
done
below is result
[elvin@TestBed$]./wh1
1,3,5,7,9,
until
until statement will do the command if the condition is false
below is the example
#!/bin/bash
i=1;
until [ $i -gt 10 ];
do
echo $i;
let i=$i+1
done
below is the result
[elvin@TestBed$]./ut
1,2,3,4,5,6,7,8,9,10,
select
below is the example
#!/bin/bash
#menu1
clear
select menu
do
echo "you choose $REPLY is $menu"
done
below is the result
layout:
[elvin@Testbed$]./menu1 Slackware Redhat Mandrake
1) Slackware
2) Redhat
3) Mandrake
#? 1
you choose 1 is Slackware