shell脚本--if语句

单分支结构:

语法:

if 条件测试 ;then
命令序列
fi

需求:
编写脚本,由用户输入用户名,如果用户不存在,则创建该用户,并设置密码为123456
脚本

#!/bin/bash
read -p "Input username: " name
id $name &> /dev/null
if [ $? -ne 0 ]; then
	useradd $name
	echo "123456" | passwd --stdin $name &> /dev/null
	echo "$name create finished,the password is 123456"
fi

关于取反的一种用法

#!/bin/bash
read -p "Input username: " name
if  ! id $name &> /dev/null; then
	useradd $name
	echo "123456" | passwd --stdin $name &> /dev/null
	echo "$name create finished,the password is 123456"
fi

双分支结构:

语法:

if 条件测试 ;then 
命令序列
else 
命令序列
fi

编写脚本,由用户输入用户名,
如果用户不存在,则创建该用户,并设置密码为123456;
否则,提示用户已经存在

#!/bin/bash
read -p "Input username: " name
if ! id $name &> /dev/null; then
useradd $name
	echo "123456" | passwd --stdin $name &> /dev/null
	echo "$name create finished,the password is 123456"
else
	echo "$name already exist"
	fi

编写脚本,由用户输入用户名,判断该用户的uid及gid,如果相同,则显示Good user;
否则显示Bad user.

#!/bin/bash
read -p "Input username: " name
user_id=`id -u $name`
group_id=`id -g $name`
if [ $user_id -eq $group_id ];then
	echo "Good user."
else
	echo "Bad user."
fi

多分支结构

语法:

if 条件测试1
then 命令序列
elif 条件测试2
then 命令序列
elif 条件测试3 
then 命令序列...
else 命令序列
fi

编写脚本,取出系统时间的小时,对数字进行判断
6–10 this is morning
11-13 this is noon
14-18 this is afternoon
其他 this is night

#!/bin/bash
hour=`date +%H`
if [ $hour -ge 6 -a $hour -le 10 ];then
	echo "This is morning"
elif [ $hour -ge 11 -a $hour -le 13 ];then
	echo "This is noon"
elif [ $hour -ge 14 -a $hour -le 18 ];then
	echo "This is afternoon"
else
	echo "This is night"
fi

嵌套结构

语法:

if 条件测试1	then 命令序列
	if 条件测试1	then 命令序列
	else 命令序列
	fi
else 命令序列
fi

需求

在这里插入图片描述

#!/bin/bash
read -p "Input username: " name
id $name &> /dev/null
if [  $? -eq 0   ];then
echo "$name 存在"
else
        useradd $name
        echo "$name create finished"
        read -p "请输入用户密码: "  pass
                if [ ${#pass}  -ge  7  ];then    // ${#pass} 调的是变量的字符个数
                echo "$pass" | passwd --stdin $name
                echo "$name 用户密码是 $pass"
                else
                echo "密码不合格" 
                fi
fi
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值