sh -n useradd.sh
多个条件
AND [ condition1 -a condition2 ] [ condition1 ] && [ condition2 ]
OR [ condition1 -o condition2 ] [ condition1 ] || [ condition2 ]
3、shell 逻辑控制语句
分支判断语句
if
case
循环结构
for
while
until
if condition;then
statement
statement
fi
举例:
!/bin/bash
read -p "name " name
read -p "secret " password
useradd $name
echo "$password" | passwd --stdin $name &> /dev/null
echo "用户$name已创建,密码为$password"
if condition;then
statement
statement
else
statement
statement
fi
举例:
[root@test shell]# cat if_useradd.sh
#!/bin/bash
read -p "name " name
id $name &> /dev/null
if [ $? -ne 0 ];then
useradd $name
read -p "secret " password
echo "$password" | passwd --stdin $name &> /dev/null
echo "用户$name已创建,密码为$password"
else
echo "用户 $name 已在"
fi
解析 同种用法:
[root@test shell]# cat if2_useradd.sh
#!/bin/bash
read -p "name " name
if id $name &> /dev/null;then
echo "用户 $name 已在"
else
useradd $name
read -p "secret " password
echo "$password" | passwd --stdin $name &> /dev/null
echo "用户$name已创建,密码为$password"
fi
if condition;then
statement
statement
elif condition;then
statement
statement
else
statement
statement
fi
举例
[root@test shell]# cat if_time.sh
#!/bin/bash
hour=`date +%H`
if [ $hour -ge 9 -a $hour -le 11 ];then
echo "morning"
elif [ $hour -ge 12 -a $hour -le 14 ];then
echo "noon"
elif [ $hour -ge 14 -a $hour -le 18 ];then
echo "afternoon"
else
echo "ngint"
fi
用法4:嵌套if
if condition;then
if condition;then
statement
statement
else
statement
statement
fi
else
statement
statement
fi
[root@test shell]# cat if_exis.sh
#!/bin/bash
read -p "backup file: " file
if [ -e $file ];then
read -p "backup dir: " dir
if [ -e $dir ];then
cp $file $dir
echo "已备份"
else
mkdir -p $dir
cp $file $dir
echo "已备份"
fi
else
echo "file is not exis"
fi
basename 文件名
basedir 文件所在的路径
case分支结构
case variable in
value1)
statement
statement
;;
value2)
statement
statement
value3)
statement
statement
;;
esac
basename 文件名
basedir 文件所在的路径
因篇幅问题不能全部显示,请点此查看更多更全内容