短路操作符
&&
||
&& 连接的是完整的命令


比较下面结果
#[ 1 -gt 2 ] && echo "OK"

#[ 3 -gt 2 ] && echo "OK"



#[ 1 -gt 2 ] || echo "OK"


#[ 4 -gt 2 ] || echo "OK"


echo $? 显示上次命令的状态是否成功

grep "^root" /etc/passwd && (who |grep "^root"|wc -l)

grep "^root" /etc/passwd &>/dev/null && (who |grep "^root"|wc -l)

grep "^root" /etc/passwd &>/dev/null ||echo "pelase give me a correct name, try again\!"


#!/bin/bash
if [ grep "^$1\>" /etc/passwd &>/dev/null]
then
{
who|grep "^$1\>"|wc -l;
who|grep "^$1\>"|cut -d' '-f14;
}
else
echo "pelase give me a correct name, try again! "
fi






#!/bin/bash
grep "^$1" /etc/passwd &>/dev/null && echo $1 && (who |grep "^$1"|wc -l ) && (who |cut -d" " -f12 )

grep "^$1" /etc/passwd &>/dev/null || echo "please input a right username,try again! "


here document: <<
实例1):
#!/bin/bash
cat >> FILE <<EOF
This is the first line,
the second line.
EOF

实例解释:创建一个文件FILE,把两个EOF中间的内容追加到新建的文件中去

实例2)
创建newscript.sh脚本,实现创建脚本时自动加载默认行
#!/bin/bash
if ! grep "^#!" $1 &> /dev/null;then
cat>>$1<<EOF
#!/bin/bash
#Author:zby
#Date & Time:`date + "%F %D"`
#Description:

EOF
fi
vim +5 $1



然后把newscript.sh放入 /bin 目录下,以后创建脚本用“#newscript.sh FILE”就可以了

实例:
一次添加20个用户,用户名和密码相同
#!/bin/bash
for I in {1..20};do
if ! cut -d: -f1 /etc/passwd | grep "^user${I}$" &> /dev/null;then
useradd user$I
echo "user$I" | passwd --stdin user$I
fi
done

删除用户
userdel -r(同时删除家目录)

实例:
#/bin/bash
for [1..30];do
if cut -d: -f1 /etc/passwd | grep "^user${I}$" &> /dev/null ;then
useradd -r user$I
fi
done





date + "%s"(现在离1970年1月1日经过了多少秒,除以86400得出天数)

#!/bin/bash
[ ! $USER=root ] && echo "only root can execute this script" && exit 1
let X=$((`date +"%s"`/86400))
FILE='/etc/shadow'
while read LINE
do
U=`echo $LINE | cut -d: -f1 `
let I=`echo $LINE | cut -d: -f5 `
if [ $((I-X)) le 10 ];then
echo "please change $U's passwd ! "
fi

done < $FILE



可以设置选项的脚本:
getopts命令
while getopts ":abcd" SWITCH;do // :忽略getopts本身的错误信息
case $SWITCH in
a);;
b);;
c);;
d);;
\?);;
esac

done

实例:输入选项就可以添加用户
userad.sh
#!/bin/bash
usage() {
echo -e "\033[31mUsage:\003[0m`basename $0` [-u UID] username"
}
while getopts ":u:" SWITCH ;do
case $SWITCH in
u)
NEWUID=$OPTARG
cut -d: -f3 /etc/passwd | grep "^NEWUID" &> /dev/null && echo "UID exists."&& exit 1
;;
\?)
usage
exit 1
;;
esac
done

NGID=$[`cut -d: -f3 /etc/group | grep -v "65534" |sort -n |tail -1`+1]

NUID=$[`cut -d: -f3 /etc/passwd | grep -v "65534" |sort -n |tail -1`+1]
TODAY=$[`date +"%s"`/86400]
#groupadd
if ! cut -d: -f1 /etc/group |grep $1 &> /dev/null;do
echo "$1:x:$NGID: ">> /etc/group
else
echo "group $1 is already exist";exit 1
fi
#useradd
if ! cut -d: -f1 /etc/passwd |grep $1 &> /dev/null;do
echo "$1:x:${NEWUID:=$NUID}:$NGID::/home/$1:/bin/bash" >> /etc/passwd
echo "$1:!!:$TODAY:0:99999:7:::" >> /etc/shadow
else
echo "user $1 is already exist";exit 1
fi
#home directory
cp -r /etc/skel /home/$1
chown -R $1:$1 /home/$1
chmod -R go=--- /home/$1