选择分支可分为三类:
1.单分支: if [ ] ;then
. .
fi
example: vim a.sh
#!/bin/bash
if [ -e /etc/issue ] ; then
echo "/etc/issue's info : "
ls -l /etc/issue
fi
2.双分支:if [ ];then
..
else
..
fi
example:判断/etc/passwd下是否存在root,如果存在,输出“root exist”,否则输出“root not exist”
vim b.sh
#!/bin/bash
if cut -d: -f1 /etc/passwd | grep "^$root$" &> /dev/null;then
echo "root exist."
else
echo "root not exist."
fi
3.多分支:if [ ];then
..
elif [ ];then
..
elif [ ];then
..
else
..
fi
example: vim c.sh
#!/bin/bash
if [ -e $1 ];then
if [ -f $1 ];then
echo "$1 is a common file."
elif [ -d $1 ];then
echo " $1 is a directory."
else
echo "$1 is unkown."
fi
else
echo "Please give me a correct file."
exit 3
fi
4.写一个脚本实现:密码过期,提示用户修改:
vim d.sh
#!/bin/basn
[ ! $user='root' ] && echo "Only root can execute this script." && exit 1
myfile='/etc/shadow'
today=$[ `date + "%s"`/86400 ] (据元年1970到现在所经历的天数)
if [ -e $myfile ];then
while read line;do
username=`echo $line | cut -d: -f1`
let maxday=`echo $line | cut -d: -f5`
[ $[$maxday-$today] -lt 10 ] && echo "${username}'s passwd needs to change. "
done < $myfile
fi
转载于:https://blog.51cto.com/chenxizhuimeng/470490