实例
1:判断目录$doiido是否存在,若不存在,则新建一个 if [ ! -d "$doiido"]; then
mkdir "$doiido"
fi
2:判断普通文件$doiido是否存,若不存在,则新建一个 if [ ! -f "$doiido" ]; then
touch "$doiido"
fi
3:判断$doiido是否存在并且是否具有可执行权限 if [ ! -x "$doiido"]; then
mkdir "$doiido"
chmod +x "$doiido"
fi
4:是判断变量$doiido是否有值 if [ ! -n "$doiido" ]; then
echo "$doiido is empty"
exit 0
fi
5:两个变量判断是否相等 if [ "$var1" = "$var2" ]; then
echo ‘$var1 eq $var2‘
else
echo ‘$var1 not eq $var2‘
fi
6:测试退出状态: if [ $? -eq 0 ];then
echo ‘That is ok‘
fi
7:数值的比较: if [ "$num" -gt "150" ]
echo "$num is biger than 150"
fi
8:a>b且a<c (( a > b )) && (( a < c ))
[[ $a > $b ]] && [[ $a < $c ]]
[ $a -gt $b -a $a -lt $c ]
9:a>b或a<c (( a > b )) || (( a < c ))
[[ $a > $b ]] || [[ $a < $c ]]
[ $a -gt $b -o $a -lt $c ]
10:检测执行脚本的用户 if [ "$(whoami)" != ‘root‘ ]; then
echo "You have no permission to run $0 as non-root user."
exit 1;
fi
上面的语句也可以使用以下的精简语句 [ "$(whoami)" != ‘root‘ ] && ( echo "You have no permission to run $0 as non-root user."; exit 1 )
11:正则表达式 doiido="hero"
if [[ "$doiido" == h* ]];then
echo "hello,hero"
fi
============其他例子============
1、查看当前操作系统类型 #!/bin/sh
SYSTEM=`uname -s`
if [ $SYSTEM = "Linux" ] ; then
echo "Linux"
elif [ $SYSTEM = "FreeBSD" ] ; then
echo "FreeBSD"
elif [ $SYSTEM = "Solaris" ] ; then
echo "Solaris"
else
echo "What?"
fi
2、if利用read传参判断 #!/bin/bash
read -p "please input a score:" score
echo -e "your score [$score] is judging by sys now"
if [ "$score" -ge "0" ]&&[ "$score" -lt "60" ];then
echo "sorry,you are lost!"
elif [ "$score" -ge "60" ]&&[ "$score" -lt "85" ];then
echo "just soso!"
elif [ "$score" -le "100" ]&&[ "$score" -ge "85" ];then
echo "good job!"
else
echo "input score is wrong , the range is [0-100]!"
fi
3、判断文件是否存在 #!/bin/sh
today=`date -d yesterday +%y%m%d`
file="apache_$today.tar.gz"
cd /home/chenshuo/shell
if [ -f "$file" ];then
echo "OK"
else
echo "error $file" >error.log
mail -s "fail backup from test" loveyasxn924@126.com <error.log
fi
echo "checking disk_d..."
if [ $a -eq 0 ]; then
echo "disk_d is not exsit,now creating..."
sudo mount -t ntfs /dev/disk/by-label/software /media/disk_d
else
echo "disk_d exits"
fi
echo "checking disk_e..."
if [ $b -eq 0 ]; then
echo "disk_e is not exsit,now creating..."
sudo mount -t ntfs /dev/disk/by-label/elitor /media/disk_e
else
echo "disk_e exits"
fi
echo "checking disk_f..."
if [ $c -eq 0 ]; then
echo "disk_f is not exsit,now creating..."
sudo mount -t ntfs /dev/disk/by-label/work /media/disk_f
else
echo "disk_f exits"
fi