jackgaolei

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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  阅读(225)  评论(0编辑  收藏  举报