语法: if 条件测试 then 命令序列 fi
示例: 需求:编写脚本,由用户输入用户名,如果用户不存在,则创建该用户,并设置密码为123456 演示: #!/bin/bash read -p “lnput username: " name id $name &> /dev/null if[ $? -ne 0 ]; then useradd $name echo “123456” | passwd --stdin KaTeX parse error: Expected 'EOF', got '&' at position 6: name &̲> /dev/null ech…name create finished,the password id 123456” fi
语法: if then 命令序列 else 命令序列 fi 需求:编写脚本,由用户输入用户名,如果用户不存在,则创建该用户,并设置密码为123456。否则,提示用户已存在 示例: #!/bin/bash read -p “lnput username: " name #id $name &> /dev/null #if [ $? -ne 0] ; then if ! id $name &> /dev/null ; then useradd $name echo"123456” | passwd --stdin KaTeX parse error: Expected 'EOF', got '&' at position 6: name &̲> /dev/null ech…name create finished,the password is 123456" else echo “$name already exist” fi
语法: if 条件测试1 then 命令序列 elif 条件测试2 then 命令序列 elif 条件测试3 then 命令序列 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 要求: 输入用户名已存在就提示存在,若不存在就创建用户然后输入密码,若密码大于7位就创建用户。若密码小于7位提示密码不符合要求 示例: read -p “Input username: " name id $name &> /dev/null if [ ? − e q 0 ] ; t h e n e c h o " ? -eq 0 ];then echo " ?−eq0];thenecho"name 存在” else useradd n a m e e c h o " name echo " nameecho"name create finished" #echo “123456” | passwd --stdin $name &> /dev/null read -p “请输入用户密码: " pass if [ KaTeX parse error: Expected '}', got '#' at position 2: {#̲pass} -ge 7 …pass” | passwd --stdin n a m e e c h o " name echo " nameecho"name 用户密码是 $pass" else echo “密码不合格” fi fi