学习记录17
bash脚本编程之六 使用脚本选项及组合条件测试
写一个脚本:
1、添加10个用户user1到user10,密码同用户名,但要求只有用户不存在情况下才能添加
#!/bin/bash
#
for I in {1..10}; do
if id user$I &> /dev/null;then
echo "user$I exists."
else
useradd user$I
echo user$I | passwd --stdin user$I &> /dev/null
echo "add user user$I finished."
fi
done
扩展:
接收一个参数:
add:添加用户 user1..user10
del:删除用户 user1..user10
其他退出
#!/bin/bash
#
if [ $# -lt 1 ]; then
echo "Usage: demo ARG"
exit 7
fi
if [ $1 == '--add' ]; then
for I in {1..10};do
if id user$I &> /dev/null; then
echo "user$I exists."
else
useradd user$I
echo user$I | passwd --stdin user$I &> /dev/null
echo "add user user$I finished."
fi
done
elif [ $1 == '--del' ]; then
for I in {1..10}; do
if id user$I &> /dev/null; then
userdel -r user$I
echo "delete user$I finished."
else
echo "no user$I"
fi
done
else
echo "unknow arg"
exit 8
fi
模拟选项和参数(逗号隔开)添加用户
#!/bin/bash
#
if [ $1 == '--add' ]; then
for I in `echo $2 | sed 's/,/ /g'`;do
if id $I &> /dev/null; then
echo "$I exists."
else
useradd $I
echo $I | passwd --stdin $I &> /dev/null
echo "add $I finished."
fi
done
elif [ $1 == '--del' ]; then
for I in `echo $2 | sed 's/,/ /g'`; do
if id $I &> /dev/null; then
userdel -r $I
echo "delete $I finished."
else
echo "$I not exists."
fi
done
elif [ $1 == '--help' ]; then
echo "Usage:demo.sh --add USER1,SUER2... | --del USER1,USER2... | --help"
else
echo "unkonw options"
fi
组合测试条件
-a:与关系
-o:或关系
!:非关系
if [ $# -gt 1 -a $# -le 3 ]
if [ $# -gt 1 ] && [ $# -le 3 ]
#!/bin/bash
#
if [ $1 == 'q' -o $1 == 'Q' -o $1 == 'Quit' -o $1 == 'quit' ]; then
echo "quiting..."
exit 0
else
echo "unknow arguement."
exit 1
fi