shell之单分支if语句

shell之单分支if语句

单分支if语句语法格式

if 条件测试
then
	命令序列
fi

ifthen可以写在同一行,如下:

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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

河 静

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值