# vi useradd.sh id abc &> /dev/null && echo"abc is exits" || useradd abc && echo"useradd is ok" # sh useradd.sh useradd is ok
tail -3 /etc/passwd
条件判断脚本示例
If条件语句:
1)单分支语句结构:
1 2 3
if 条件表达式;then 命令序列 fi
例:查询以下/qq/ww/ee是否不存在,则进行创建
1 2 3 4 5
#!/bin/bash io="/qq/ww/ee" if [ ! -d $io ];then mkdir -p $io && echo"目录不存在,并且已重新创建此目录" fi
例:查看当前登录用户
1 2 3 4
#!/bin/bash if [ $user = "abc" ];then echo"ERROR: user is not abc" fi
2)双分支语句结构:
1 2 3 4 5
if 条件表达式;then 命令序列1 else 命令序列2 fi
例:检测80服务是否启动,如果没启动则进行启动
1 2 3 4 5 6 7
#!/bin/bash netstat -anpt | grep 80 if [ $? -eq 0 ];then echo"httpd is running" else systemctl restart httpd && echo"httpd is running" fi
3)多分支语句结构:
1 2 3 4 5 6 7
if 条件表达式1;then 命令序列1 elif 条件表达式2;then 命令序列2 else 命令序列3 fi
例:判断用户输入的内容
1 2 3 4 5 6 7 8 9 10 11
#!/bin/bash read -p "hello (q,w,e,r):" oo if [ $oo = q ];then echo"$oo is pig" elif [ $oo = w ];then echo"$oo is dog" elif [ $oo = e ];then echo"$oo is aa" else echo"$oo is sb" fi