生活随笔
收集整理的這篇文章主要介紹了
Shell基础之条件判断 分支判断
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
條件判斷式語句 文件類型判斷 測(cè)試選項(xiàng)作用 -d 文件 是否是目錄 -e 文件 是否存在 -f 文件 是否是文件
整數(shù)之間的比較 測(cè)試選項(xiàng)作用 整數(shù)1 -eq 整數(shù)2 相等 整數(shù)1 -ne 整數(shù)2 不相等 整數(shù)1 -gt 整數(shù)2 大于 整數(shù)1 -lt 整數(shù)2 小于 整數(shù)1 -ge 整數(shù)2 大于等于 整數(shù)1 -le 整數(shù)2 小于等于
文件權(quán)限 測(cè)試選項(xiàng)作用 -r 文件 是否可讀 -w 文件 是否可寫 -x 文件 是否可執(zhí)行
字符串判斷 測(cè)試選項(xiàng)作用 -z 字符串 是否為空,為空返回真 -n 字符串 是否為空,非空返回真 字符串1 == 字符串2 == 字符串1 != 字符串2 !=
多重條件判斷 測(cè)試選項(xiàng)作用 判斷1 -a 判斷2 與 判斷1 -o 判斷2 或 !判斷 非
[
-d /root] &&
echo "yes" ||
echo "no"
復(fù)制代碼 單分支if語句 #!/bin/bash
test =$(env | grep
"USER" | cut
-d "=" -f 2)
if [
"$test " == root ]
then echo "Current user is root"
fi
復(fù)制代碼 #!/bin/bash
rate=$(df -h | grep
"/dev/vda1" | awk
'{print $5}' | cut
-d "%" -f 1)
if [
$rate -ge 1 ]
then echo "Warming /dev/vda1 is full !!"
fi 復(fù)制代碼 雙分支if語句 #!/bin/bash
read -t 30 -p
"Please input a dir: " dir
if [
-d "$dir " ]
then echo "yes" else echo "no"
fi
復(fù)制代碼 #!/bin/bash
test =$(ps aux | grep httpd | grep -v grep)
if [ -n
"$test " ]
then echo "$(date) httpd is ok!" >> /tmp/autostart-acc.log
else /etc/rc.d/init.d/httpd start &> /dev/null
echo "$(date) httpd restart httpd!!" >> /tmp/autostart-acc.log
fi
復(fù)制代碼 多分支if語句 #!/bin/bash
read -p
"Please input a filename : " file
if [ -z
"$file " ]
then echo "Error, please input a filename " exit 1
elif [ !
-e "$file " ]
then echo "Your input is not a file! " exit 2
elif [
-f "$file " ]
then echo "$file is a regulare file!"
elif [
-d "$file " ]
then echo "$file is a directory!"
else echo "$file is an other file!"
fi
復(fù)制代碼 多分支case語句 #!/bin/bash
read -t 30 -p
"Please input yes/no : " cho
case "$cho " in "yes" )
echo "yes" ;;
"no" )
echo "no" ;;
"*" )
echo "Please input right content" ;;
esac
復(fù)制代碼 for循環(huán) #!/bin/bash
cd /root/
test /
ls *.tar.gz > ls.log
ls *.tgz >> ls.log
for i
in $( cat ls.log )
do tar -zxf
$i & > /dev/null
done rm -rf ls.log
復(fù)制代碼 #!/bin/bash
s=0
for (( i=1;i<=100;i=i+1 ))
do s=$((
$s +
$i ))
done
echo $s
復(fù)制代碼 #!/bin/bash
read -p
"Please input user name : " -t 30 name
read -p
"Please input number of users : " -t 30 num
read -p
"Please input user pass : " -t 30 pass
if [ ! -z
"$name " -a ! -z
"$num " -a ! -z
"$pass " ]
then y=$(
echo $num | sed
's/[0-9]//g' )
if [ -z
"$y " ]
then for (( i=1;i<=
$num ;i=i+1 ))
do /usr/sbin/useradd
$name $i &> /dev/null
echo $pass | /usr/bin/passwd --stdin
$name $i &> /dev/null
done fi
fi
復(fù)制代碼 #!/bin/bash
for i
in $( cat /etc/passwd | grep /bin/bash | grep -v root | cut
-d ":" -f 1 )
do userdel -r
$i done
復(fù)制代碼 while循環(huán)和until循環(huán) #!/bin/bash
i=1
s=0
while [
$i -le 100 ]
do s=$((
$s +
$i ))i=$((
$i +1))
done echo "This sum is : $s "
復(fù)制代碼 #!/bin/bash
i=1
s=0util [
$i -ge 100 ]
do s=$((
$s +
$i ))i=$((
$i +1))
done echo "This sum is : $s "
復(fù)制代碼
總結(jié)
以上是生活随笔 為你收集整理的Shell基础之条件判断 分支判断 的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔 推薦給好友。