判断结构--Linux

if判断结构

if expression; then
    command1
    command2
fi
majun@instance-zqtg07w6:~$ vim score01.sh
majun@instance-zqtg07w6:~$ cat score01.sh
#!/bin/bash
echo -n "Please input your score:"
read SCORE
if [ "$SCORE" -lt 60 ]; then
        echo "C"
fi
if [ "$SCORE" -lt 80 -a "$SCORE" -ge 60 ]; then
        echo "B"
fi
if [ "$SCORE" -ge 80 ]; then
        echo "A"
fi

majun@instance-zqtg07w6:~$ bash score01.sh
Please input your score:99
A
majun@instance-zqtg07w6:~$ bash score01.sh
Please input your score:78
B
majun@instance-zqtg07w6:~$ bash score01.sh
Please input your score:59
C
majun@instance-zqtg07w6:~$

if/else 判断结构

if expression; then
    command
else
    command
fi
majun@instance-zqtg07w6:~$ vim check_file.sh
majun@instance-zqtg07w6:~$ cat check_file.sh
#!/bin/bash
echo -n "input your file:"
read FILE
#FILE=/etc/passwd
if [ -e $FILE ]; then
        echo "$FILE exists."
else
        echo "$FILE NOT EXISTS."
fi
majun@instance-zqtg07w6:~$ bash check_file.sh
input your file:/etc/passwd
/etc/passwd exists.
majun@instance-zqtg07w6:~$ bash check_file.sh
input your file:/etc/passwd01
/etc/passwd01 NOT EXISTS.
majun@instance-zqtg07w6:~$

if/elif/else 判断结构

if expression; then
    command1
elif expression; then
    command2
elif expression; then
    command3
else
    command4
fi
majun@instance-zqtg07w6:~$ cat score03.sh
#!/bin/bash
echo -n "Please input your score:"
read SCORE
if [ "$SCORE" -lt 60 ]; then
        echo "CCCCCCCC"
elif [ "$SCORE" -ge 60 -a "$SCORE" -lt 80 ]; then
        echo "BBBBBBBB"
else
        echo "AAAAAAAA"
fi
majun@instance-zqtg07w6:~$ bash score03.sh
Please input your score:99
AAAAAAAA
majun@instance-zqtg07w6:~$ bash score03.sh
Please input your score:80
AAAAAAAA
majun@instance-zqtg07w6:~$ bash score03.sh
Please input your score:59
CCCCCCCC
majun@instance-zqtg07w6:~$ bash score03.sh
Please input your score:78
BBBBBBBB
majun@instance-zqtg07w6:~$

case 判断结构

majun@instance-zqtg07w6:~$ vim os_type.sh
majun@instance-zqtg07w6:~$ cat os_type.sh
#!/bin/bash
OS=`uname -s`
case "$OS" in
Linux) echo "this is linux;";;
SunOS) echo "this is sun";;
*) echo "failed to type os";;
esac
echo $OS

majun@instance-zqtg07w6:~$ bash os_type.sh
this is linux;
Linux
majun@instance-zqtg07w6:~$

所有的练习脚本都在:
https://github.com/SaltNego/Learn_linux_bash

发布了61 篇原创文章 · 获赞 22 · 访问量 4258

猜你喜欢

转载自blog.csdn.net/yiqiushi4748/article/details/103811386
今日推荐