bash 编程中循环语句用法
2019-10-26 18:31:55
供稿:网友
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 语句是循环语句,当条件满足的情况下才循环,不满足则退出循环,使用格式如下:
while condition ; do
statement
…..
done
5.until 语句也是循环语句,当条件不满足的情况下循环,满足则不循环,使用格式如下:
until condition ; do
statement
…..
done
6.case 也是循环语句,使用格式如下:
case $var(变量) ; in
value1)
……
value2)
…..
*)
..
..
..
esac
脚本练习:
1.计算100以内所有能被3整除的正整数的和。
代码如下:
#!/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.计算100以内所有奇数的和以及所有偶数的和
代码如下:
#!/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下的文件的类型:
如果是普通文件,则说明其为普通文件;
如果是目录文件,则说明其为目录文件;
如果是符号链接文件,则说明其为符号链接文件;
否则,说明文件类型无法识别;
代码如下:
#!/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.写一个脚本,分别显示当前系统上所有默认shell为bash的用户和默认shell为
/sbin/nologin的用户
并统计各类shell下的用户总数,显示结果形如: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.写一个脚本:
(1)如果不存在,就创建文件/tmp/maintenance;如果存在,就事先删除