[iyunv@station01 ~]# cat test6.sh
#!/bin/bash
#
grep "\<bash$" /etc/passwd &>/dev/null
RETVAL=$?
if [ $RETVAL -eq 0 ];then
USERS=`grep "\<bash$" /etc/passwd |wc -l`
echo "The total of $USERS users is default bash shell."
else
echo "No such user."
fi
如判断当前系统上是否有用户的默认shell为bash,如有则显示其中一个用户名,否则显示没有。
1
2
3
4
5
6
7
8
9
10
11
[iyunv@station01 ~]# cat test7.sh
#!/bin/bash
#
grep "\<bash$" /etc/passwd &>/dev/null
RETVAL=$?
if [ $RETVAL -eq 0 ];then
USERS=`grep "\<bash$" /etc/passwd |head -1 |cut -d: -f1`
echo "The one of $USERS is /etc/passwd file."
else
echo "No such user."
fi
如:给定一个文件,判断是否有空白行,如有则显示有多少行,否则显示没有空白行
1
2
3
4
5
6
7
8
9
10
11
12
[iyunv@station01 ~]# cat test8.sh
#!/bin/bash
#
FILES=/etc/inittab
grep "^$" $FILES &>/dev/null
RETVAL=$?
if [ $RETVAL -eq 0 ];then
LINES=`grep "^$" $FILES |wc -l`
echo "The total of $LINES line is blank."
else
echo "No such blank line."
fi
如:给定一用户,判定其UID是否等于GID,如一样,则显示SAME,否则显示NOT THE SAME 1)方法一
1
2
3
4
5
6
7
8
9
[iyunv@station01 ~]# cat test9.sh
#!/bin/bash
#
USERNAME=user1
if [ `id -u $USERNAME` -eq `id -g $USERNAME` ];then
echo "The ${USERNAME}'s UID equal GID."
else
echo "Not the same"
fi
2)方法二
1
2
3
4
5
6
7
8
9
[iyunv@station01 ~]# cat test10.sh
#!/bin/bash
#
USERNAME=user6
if [ `grep "^\<$USERNAME\>" /etc/passwd | cut -d: -f3` -eq `grep "^\<$USERNAME\>" /etc/passwd | cut -d: -f4` ];then
echo "The ${USERNAME}'s UID equal GID."
else
echo "Not the same"
fi
SHELL中如何进行算术运算
1、定义变量时为字符型,运算时用let命令;
let 算术运算表达式,let CC=$AA+$BB
[iyunv@station01 ~]# cat test5.sh
#!/bin/bash
#
NAME=user12
if ! grep "^$NAME/>" /etc/passwd &>/dev/null;then
echo "$NAME is exsit"
exit 23
fi
if id $NAME &>/dev/null;then
echo "$NAME is esist."
else
useradd $NAME
echo $NAME |passwd --stdin $NAME &>/dev/null
echo "Add $NAME is successfully."
fi
[iyunv@station01 ~]# cat test8.sh
#!/bin/bash
#
FILES=/etc/inittabaa
if [ ! -e $FILES ];then
echo "No such file."
exit 20
fi
grep "^$" $FILES &>/dev/null
RETVAL=$?
if [ $RETVAL -eq 0 ];then
LINES=`grep "^$" $FILES |wc -l`
echo "The total of $LINES line is blank."
else
echo "No such blank line."
fi
执行结果
1
2
3
4
[iyunv@station01 ~]# ./test8.sh
No such file.
[iyunv@station01 ~]# echo $?
20