There are three main types of shell loops: for, while, until
There are two main types of judgments on the branch of shell: if, case
1. For loop
#!/bin/bash
for file in $(ls /tmp/test/mytest |grep sh) //For in format is the basic format of shell for, root js for in similar
do
echo $file
done
for ((i=0;i<10;i++)) //Note that it is double brackets, and it is easy to make mistakes due to the influence of other languages.
do
echo -n $i
done
echo \ //Output line break
for i in 0 1 2 3 4 5 6 7 8 9
do
echo -n $i
done
echo \
for i in "0 1 2 3 4 5 6 7 8 9" //There is a difference above this root. This loop only loops once, and it is just a variable in the double quotes
do
echo -n $i
done
exit 0
2. While loop
#!/bin/bash
i=0
while ((i<10))
do
echo $i
((i += 1))
done
i=0
while [ $i -lt 10 ] //Note the spaces on the two sides inside the brackets
do
echo $i
let "i+=1" //Add 1
done
exit 0
Three, until loop
#!/bin/bash
END_CONDITION=end
until [ "$var1" = "$END_CONDITION" ] //The variables set by the read variables are equal when the variables are set, otherwise the loop will be looped forever
do
echo "Input variable #1 "
echo "($END_CONDITION to exit)"
read var1
echo "variable #1 = $var1"
echo
done
exit 0
Four, if statement
#!/bin/bash
echo "Input a number #1 "
read num
echo "variable #1 = $num"
if [ $num -lt 60 ] //Note the - in front of lt, it is easy to forget
then
echo "you are not pass"
elif [ $num -lt 70 ] && [ $num -ge 60 ] //Judgement of multiple conditions
then
echo "pass"
elif [[ $num -lt 85 && $num -ge 70 ]] //If put together, be careful to be bracketed in both squares and do not write it as [ $num -lt 85 && $num -ge 70 ]
then
echo "good"
elif (( $num <= 100 )) && (( $num >= 85 )) //For people with language foundation, this writing makes people feel very comfortable. Don’t forget that it is double brackets
then
echo "very good"
else
echo "num is wrong"
fi
exit 0
Five, case statement
#!/bin/sh
case $1 in
start)
echo "start ok"
;; //Be careful, be careful of the double semicolon
stop)
echo "stop ok"
;;
restart)
echo "restart ok"
;;
*)
echo "no param"
;;
esac //Be careful to close the tag
exit 0
[root@krlcgcms01 forif]# sh stop
stop ok