if [ ! -x "$doiido"]; then mkdir"$doiido" chmod +x "$doiido" fi
4.是判断变量$doiido是否有值
1 2 3 4
if [ ! -n "$doiido" ]; then echo"$doiido is empty" exit 0 fi
5.两个变量判断是否相等
1 2 3 4 5
if [ "$var1" = "$var2" ]; then echo'$var1 eq $var2' else echo'$var1 not eq $var2' fi
6.测试退出状态:
1 2 3
if [ $? -eq 0 ];then echo'That is ok' fi
7.数值的比较:
1 2 3
if [ "$num" -gt "150" ];then echo"$num is biger than 150" fi
8.a>b且a<c
1 2 3
(( a > b )) && (( a < c )) [[ $a > $b ]] && [[ $a < $c ]] [ $a -gt $b -a $a -lt $c ]
9.a>b或a<c
1 2 3
(( a > b )) || (( a < c )) [[ $a > $b ]] || [[ $a < $c ]] [ $a -gt $b -o $a -lt $c ]
10.检测执行脚本的用户
1 2 3 4
if [ "$(whoami)" != 'root' ]; then echo"You have no permission to run $0 as non-root user." exit 1; fi
上面的语句也可以使用以下的精简语句
1
[ "$(whoami)" != 'root' ] && ( echo"You have no permission to run $0 as non-root user."; exit 1 )
11.正则表达式
1 2 3 4
doiido="hero" if [[ "$doiido" == h* ]];then echo"hello,hero" fi
8. ===其他例子===
1. 查看当前操作系统类型
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#!/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传参判断
1 2 3 4 5 6 7 8 9 10 11 12
#!/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. 判断文件是否存在
1 2 3 4 5 6 7 8 9 10 11
#!/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
4. 这个脚本在每个星期天由cron来执行。如果星期的数是偶数,他就提醒你把垃圾箱清理:
1 2 3 4 5
#!/bin/bash WEEKOFFSET=$[ $(date +"%V") % 2 ] if [ $WEEKOFFSET -eq "0" ]; then echo"Sunday evening, put out the garbage cans." | mail -s "Garbage cans out" your@your_domain.org fi
#! /bin/sh dir_d=/media/disk_d dir_e=/media/disk_e dir_f=/media/disk_f a=`ls$dir_d | wc -l` b=`ls$dir_e | wc -l` c=`ls$dir_f | wc -l` 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