shell脚本的简单练习

1、在当前主机编写脚本文件history_max.sh显示主机中执行频率最高的前5个命令。

#创建/shell、chap01目录文件并切换至chap01目录下。
[root@server ~]# mkdir /shell
[root@server shell]# mkdir chap01
[root@server shell]# cd chap01/
#编辑history_max.sh文件
[root@server chap01]# vim history_max.sh

#编辑history_max.sh内容:

#!/bin/bash
history -w history    #将当前历史命令缓冲区命令写入历史命令文件中
sort history | uniq -c | sort -t " " -k 1 -nr | head -5

#运行脚本文件history_max.sh,结果如下
[root@server chap01]# source ./history_max.sh
     78 ll
     13 ll /sc
     11 tree
     11 ls
     11 cd



2、判断主机是否存在rhel用户,如果存在则设置密码为redhat,如果不存在则创建用户并设置密码。

[root@server shell]# mkdir chap02
[root@server shell]# cd chap02/
[root@server chap02]# vim test.sh

#脚本文件test.sh内容:
#!/bin/bash

useradd rhel && passwd rhel  || echo redhat | passwd --stdin rhel

#检测结果:
[root@server chap02]# source ./test.sh

useradd: user 'rhel' already exists
Changing password for user rhel.
passwd: all authentication tokens updated successfully.

#删除用户rhel,检测脚本是否能创建并成功设置密码
[root@server chap02]# userdel -r rhel
[root@server chap02]# source ./test.sh
Changing password for user rhel.
New password:
BAD PASSWORD: The password is shorter than 8 characters
Retype new password:
passwd: all authentication tokens updated successfully.

3、通过设置变量HISTTIMEFORMAT,使得当执行history命令时输出格式如下:[2022-12-25 16:53:42][root]history

#时间格式:[`date "+%F %T"`]
#用户名格式:[`whoami`]
[root@server ~]# HISTTIMEFORMAT=[`date "+%F %T"`][`whoami`]
[root@server ~]# history
  675  [2022-12-27 14:02:26][root]HISTTIMEFORMAT=[`date "+%F %T"`][`whoami`]
  676  [2022-12-27 14:02:26][root]history

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值