shell之单分支if语句
单分支if语句语法格式
if 条件测试
then
命令序列
fi
if
和then
可以写在同一行,如下:
if 条件测试;then
命令序列
fi
单括号用-a
双括号用&&
单括号中间连接用&&
1.测试脚本,在[]
中不允许有&&
和||
的使用出现
#!/bin/bash
read -p "请输入用户名:" user
read -s -p "请输入密码:" pass
if [ ! -z "$user" ];then
if [ ! -z "$pass" ];then
useradd "$user"
echo "$pass" | passwd --stdin "$user"
fi
fi
账户名为空的话,也不会执行设置密码操作了。
2.测试脚本,使用双括号[[]],双括号不能与-a
、-o
使用,只能用&&
、||
注意:括号两边有空格
#!/bin/bash
read -p "请输入用户名:" user
read -s -p "请输入密码:" pass
if [[ ! -z "$user" && ! -z "$pass" ]];then
useradd "$user"
echo "$pass" | passwd --stdin "$user"
fi
此时,user和pass都不为空的时候,才会执行下面的命令
3.测试脚本,使用[]
、-a
#!/bin/bash
read -p "请输入用户名:" user
read -s -p "请输入密码:" pass
if [ ! -z "$user" -a ! -z "$pass" ];then
useradd "$user"
echo "$pass" | passwd --stdin "$user"
fi
4.测试脚本,虽然不能在[]
中使用&&
、||
,但可以多次使用[]
,中间用&&
、||
进行逻辑判断
#!/bin/bash
read -p "请输入用户名:" user
read -s -p "请输入密码:" pass
if [ ! -z "$user" ] && [ ! -z "$pass" ];then
useradd "$user"
echo "$pass" | passwd --stdin "$user"
fi
5.任何有返回值的命令都可以写在if后面
#!/bin/bash
if grep -i intel -q /proc/cpuinfo;then
echo "Intel cpu"
fi
if ! mkdir "/media/cdrom";then
echo "failed to create directory"
fi
if ! yum -y install xeyes;then
echo "failed to install xeyes"
fi
if systemctl is-active $1 &>/dev/null;then
echo "$1 已经启动"
else
echo "$1 未启动......"
fi