您的位置:首页 > 运维架构 > Shell

Linux基础入门及系统管理01-bash脚本编程之三整数测试及算术运算18

2014-04-15 16:59 1261 查看
练习1,写一个脚本:
1、判断当前系统上是否有用户的默认shell为bash;
2、如果有,就显示有多少个这类用户;否则,就显示没有这类用户;
参考答案:#nano usershell.sh
#!/bin/bash
#
grep "\<bash$" /etc/passwd &> /dev/null
RETVAL=$?
if [ $RETVAL -eq 0 ];then
USER=`grep "\<bash$" /etc/passwd | wc -l`
echo "The shells have got $USER users is bash."
else
echo "Not such users."
fi
#bash usershell.sh

练习2,写一个脚本:
1、判断当前系统上是否有用户的默认shell为bash;
2、如果有,就显示其中一个的用户名;否则,就显示没有这类用户;
参考答案:#nano usershell.sh
#!/bin/bash
#
grep "\<bash$" /etc/passwd &> /dev/null
RETVAL=$?
if [ $RETVAL -eq 0 ];then
USER=`grep "\<bash$" /etc/passwd | head -l` | cut -d: -f1
echo "The user $USER is bash."
else
echo "Not such users."
fi
#bash usershell.sh
练习3,写一个脚本:
1、给定一个文件,比如/etc/inittab;
2、判断这个文件中是否有空白行;
3、如果有,则显示其空白行数;否则,显示没有空白行。
参考答案:#nano space.sh
#!/bin/bash
#
grep '^$' /etc/inittab &> /dev/null
SPACE=$?
if [ $SPACE -eq 0 ];then
SPACELINE=`grep '^$' /etc/inittab | wc -l`
echo "Space $SPACELINE lines."
else
echo "Not space line."
fi
#bash space.sh

练习4,写一个脚本:
1、给定一个用户,判断其UID与GID是否一样;
2、如果一样,就显示此用户为“good guy”;否则,就显示此用户为“bad guy”。
参考答案:#nano uidgid.sh
#!/bin/bash
#
USERNAME=nick
if !`grep '\<$USERNAME\>' /etc/passwd &> /etc/null`;then
echo "User:$USERNAME not exists."
exit 1
fi
USERUID=`grep '\<$USERNAME\>' /etc/passwd | cut -d: -f3`
USERGID=`grep '\<$USERNAME\>' /etc/passwd | cut -d: -f4`
if [ $USERUID -eq $USERGID];then
echo "The $USERNAME is good guy."
else
echo "The $USERNAME is bad guy."
fi
# bash uidgid.sh

The nick is good guy.

练习5,写一个脚本:
1、给定一个用户,获取其密码警告期限;
2、而后判断用户最近一次修改密码时间距今天是否已经小于警告期限;
提示:算术运算的方法$[$A-$B],表示变量A的值减去变量B的值的结果;
如果小于,则显示“warning”;否则,就显示“OK”;
参考答案:# nano userpasswd.sh
#!/bin/bash
#
NAME=nick
TIME1=`date +%s`--------------------------------圆整,小数点后都省略
let TIME2=$TIME1/86400
TIME3=`grep $NAME /etc/shadow | cut -d: -f3`
TIME4=`grep $NAME /etc/shadow | cut -d: -f5`
TIME5=$(($TIME4-($TIME2-$TIME3)))
TIME6=`grep $NAME /etc/shadow | cut -d: -f6`
if [ $TIME5 -lt $TIME6 ];then
echo "Waring."
else
echo "OK."
fi
# bash userpasswd.sh

OK.

一、shell中如何进行算术运算
1、let 算术运算表达式;
如:# A=3
# B=6
# let C=$A+$B
# echo $C
9
2、$ [算术运算表达式];
如:C=$[$A+$B]
3、$(($A+$B));
如:C=$(($A+$B))
4、expr 算术运算符,表达式中各操作数及运算符之间要有空格,而且要使用命令引用;
如:C=`expr $A + $B` 。

本文出自 “Jessen Liu的博文” 博客,请务必保留此出处http://zkhylt.blog.51cto.com/3638719/1395902
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: