项目场景:
编写Linux shell自动判卷脚本过程中,使用到history命令时,如何显示命令执行时间问题的解决。
问题描述
Linux中的history命令默认只会显示两列,序号和命令,无法显示时间,如下所示:
[root@yjh ~]# history
1 fdisk -l
2 fdisk /dev/sda
3 init 0
4 fdisk
5 startx
6 ifconfig
7 ifconfig eth0 192.168.111.2
8 ifconfig
9 ifconfig eth0 192.168.111.2
10 ifconfig eth1 192.168.111.
原因分析:
history命令的执行结果是系统默认的两列结果,如需显示更多信息,需配置HISTTIMEFORMAT环境变量
解决方案:
-
仅使本次登录有效,直接执行如下命令:
export HISTTIMEFORMAT="%F %T "
执行结果如下,会看到已经出现了命令执行的时间
[root@yjh ~]# history 1 2022-06-01 22:28:30 fdisk -l 2 2022-06-01 22:28:30 fdisk /dev/sda 3 2022-06-01 22:28:30 init 0 4 2022-06-01 22:28:30 fdisk 5 2022-06-01 22:28:30 startx 6 2022-06-01 22:28:30 ifconfig 7 2022-06-01 22:28:30 ifconfig eth0 192.168.111.2 8 2022-06-01 22:28:30 ifconfig 9 2022-06-01 22:28:30 ifconfig eth0 192.168.111.2 10 2022-06-01 22:28:30 ifconfig eth1 192.168.111.2
-
若要使每次都生效,则需要设置系统环境变量,首先打开/etc/profile文件
vim /etc/profile
在文件末尾加上该条命令
export HISTTIMEFORMAT="%F %T "
如下所示:
保存并退出后,执行source /etc/profile命令或重启后,即可永久生效,每次使用history命令即可显示命令执行时间,