linux 控制结构
Posted cxhfuujust
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了linux 控制结构相关的知识,希望对你有一定的参考价值。
一.if
注:
格式1、格式2:一个条件一个命令;
格式3:一个条件两个命令;
格式4:两个条件三个命令,注意条件的写法。
例1:
#!/bin/sh
#ifTest
#to show the method of if
echo -e "Enter the first integer:\\c"
read FIRST
echo -n "Enter the second integer:"
read SECOND
if [ "$FIRST" -gt "$SECOND" ]
then
echo "$FIRST is greater than $SECOND"
elif [ "$FIRST" -lt "$SECOND" ]
then
echo "$FIRST is less than $SECOND"
else
echo "$FIRST is equal to $SECOND"
fi
执行:
[root@cdh1 sh]# ./test.sh
Enter the first integer:7
Enter the second integer:7
7 is equal to 7
[root@cdh1 sh]# ./test.sh
Enter the first integer:8
Enter the second integer:7
8 is greater than 7
[root@cdh1 sh]#
例2:
#!/bin/bash
#5.sh
#declare a,b ;
a=$1
b=$2
if [ "$a" = "$b" ] ;then
echo "a=b"
else
echo "a!=b"
fi
例3.
read -p "Please input (Y/N): " yn
if [ "$yn" = "Y" ] || [ "$yn" = "y" ]; then
echo "OK, continue"
exit 0
fi
if [ "$yn" = "N" ] || [ "$yn" = "n" ]; then
echo "Oh, interrupt!"
exit 0
fi
echo "I don\'t know what your choice is" && exit 0
执行
[root@cdh1 sh]# ./2.sh
Please input (Y/N): y
OK, continue
二.case
例1
#!/bin/sh
#caseTest
#to test the method of case
USER=`whoami`
case $USER in
root)echo "You can do all the operations"
;;
Dave)echo "You can do some operations"
;;
*)echo "Sorry,you can not do anything"
;;
esac
执行:
[root@cdh1 sh]# ./test.sh
You can do all the operations
三、for
例子:
#!/bin/sh
#forTest
#to test the method of for
COUNTER=0
for aa in *
do
echo ${aa}
COUNTER=`expr $COUNTER + 1`
done
echo "There are $COUNTER files in `pwd` "
执行
[root@cdh1 sh]# ./test.sh
2
2.sh
3.sh
4.sh
5.sh
function.sh
test.sh
There are 7 files in /opt/data/sh
以上是关于linux 控制结构的主要内容,如果未能解决你的问题,请参考以下文章