bash 編程中循環(huán)語句用法
2019-10-26 18:31:55
供稿:網(wǎng)友
1.if 是單分支語句,使用格式如下:
if condition ; then
statement
…..
fi
2.if … else 是雙分支語句,使用格式如下:
if condition ; then
statement
….
else
statement
….
fi
3.if …elif…elif…else 是多分支語句,使用格式如下:
if condition ; then
statement
….
elif condition ; then
statement
…..
elif condition ; then
statement
…..
.
.
.
else
statement
….
fi
4.while 語句是循環(huán)語句,當(dāng)條件滿足的情況下才循環(huán),不滿足則退出循環(huán),使用格式如下:
while condition ; do
statement
…..
done
5.until 語句也是循環(huán)語句,當(dāng)條件不滿足的情況下循環(huán),滿足則不循環(huán),使用格式如下:
until condition ; do
statement
…..
done
6.case 也是循環(huán)語句,使用格式如下:
case $var(變量) ; in
value1)
……
value2)
…..
*)
..
..
..
esac
腳本練習(xí):
1.計(jì)算100以內(nèi)所有能被3整除的正整數(shù)的和。
代碼如下:
#!/bin/bash
declare -i sum=0
for I in {1..100}; do
if [ $[$I%3] -eq 0 ]; then
let sum+=$I
fi
done
echo " the sum is :$sum"
2.計(jì)算100以內(nèi)所有奇數(shù)的和以及所有偶數(shù)的和
代碼如下:
#!/bin/bash
# echo "exercise"
declare -i sum1=0
declare -i sum2=0
for I in {1..100}; do
if [ $[$I%2] -eq 0 ]; then
let sum1+=$I
else
let sum2+=$I
fi
done
echo " the even sum is :$sum1"
echo " the oddnumber sum is :$sum2"
3.判斷/var/log下的文件的類型:
如果是普通文件,則說明其為普通文件;
如果是目錄文件,則說明其為目錄文件;
如果是符號(hào)鏈接文件,則說明其為符號(hào)鏈接文件;
否則,說明文件類型無法識(shí)別;
代碼如下:
#!/bin/bash
file1=/var/log/*
for file in $file1 ; do
if [ -f $file ]; then
echo "$file is common file"
elif [ -d $file ]; then
echo "$file is directory file"
else
echo "$file is unknow"
fi
done
4.寫一個(gè)腳本,分別顯示當(dāng)前系統(tǒng)上所有默認(rèn)shell為bash的用戶和默認(rèn)shell為
/sbin/nologin的用戶
并統(tǒng)計(jì)各類shell下的用戶總數(shù),顯示結(jié)果形如:bash,3user,they
are:root,redhat,gentoo nologn,2user,they are:bin,ftp
代碼如下:
#!/bin/bash
file=/etc/passwd
bsh='/bin/bash'
nobsh='/sbin/nologin'
use=`cat $file | cut -d: -f1`
declare -i d1=0
declare -i d2=0
for I in $use ; do
s=`grep "^$I:" $file | cut -d: -f7`
if [ "$s" = $bsh ] ; then
let d1=$d1+1
muser=$I/,$muser
elif [ "$s" = $nobsh ] ; then
let d2=$d2+1
suser=$I/,$suser
fi
done
echo "BASH,$d1 users ,they are:"
echo $muser
echo
echo "NOLOGIN,$d2 users ,they are:"
echo $suser
5.寫一個(gè)腳本:
(1)如果不存在,就創(chuàng)建文件/tmp/maintenance;如果存在,就事先刪除