shell编程-条件判断与流程控制

1.if语句

单分支if语句

#!/bin/bash

temp=$(env | grep USER | cut -d "=" -f 2)
if [ "$temp" == "root" ]
        then
                echo "hello root"
fi
#!/bin/bash

temp=$(env | grep USER | cut -d "=" -f 2)
if [ "$temp" == "root" ];then
        echo "hello root"
fi

(判断用户是否为root,注意:if后需要加空格)

 

#!/bin/bash
temp=$(df -h | grep sda2 | awk '{print $5}' | cut -d "%" -f 1)
echo $temp
if [ "$temp" -ge "10" ];then
        echo "full"
fi

(判断根分区使用量是否大于10%)

双分支if语句

#!/bin/bash

read -t 30 -p "input file or folder name:" dir
if [ -d "$dir"  ]
        then
                echo "folder"
        else
                echo "file"
fi

(判断输入的是文件还是目录)

多分支if语句

[root@wap test]# vi if3.sh 
#!/bin/bash

read -p "input name:" name

if [ -z "$name" ]
        then
                echo "input null"
                exit 1
elif [ -e "$name"  ]
        then
                echo "file is exist"
elif [ -d "$name" ]
        then
                echo "$name is a  folder"
elif [ -f "$name" ]
        then
                echo "$name is a file"
        else
                echo "$name is not a file or folder"
fi

(判断输入的是什么文件)

 

2.多分支case语句

#!/bin/bash

read -p "please input code:" code

case $code in
"A")
        echo "beijing"
        ;;
"B")
        echo "shanghai"
        ;;
*)
        echo "unknown"
        ;;
esac

"*"代表其他情况,注意每种情况后都需要加";;"

 

3.for循环

#!/bin/bash

for i in 1 2 3 4 5
do
        echo $i
done
#!/bin/bash

cd /usr/local/test
ls *.tar > temp.txt

for i in $(cat temp.txt)
do
        tar -xvf "$i" &> /dev/null
done

(解压所有的tar文件)

注意:使用" &> /dev/null "将输出内容放入回收站,执行脚本过程中就不会报任何信息 

#!/bin/bash

sum=0

for((i=0;i<=100;i++))
do
        sum=$(( $sum+$i ))
done

echo "$sum"

 

4.while循环和until循环

while

#!/bin/bash

sum=0
index=1

while [ $index -le 100 ]
do
        sum=$(( $sum + $index  ))
        index=$(($index + 1 ))
done

echo $sum

until

#!/bin/bash

sum=0
index=1

until [ $index -gt 100  ]
do
     sum=$(( $sum+$index ))
     index=$(( $index+1 ))
done

echo $sum

  

 

  

 

posted on 2016-01-18 11:41  jackgaolei 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/jackgaolei/p/5138738.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值