日期:2014-05-16  浏览次数:20658 次

请教HISTFILE环境变量的问题。
大家好:
        请问HISTFILE环境变量是否是执行history命令是读取的命令历史记录文件?
但我发现直接在命令行中设置该环境变量  export HISTFILE="/home/testsys/cmd.hist"  后,执行history命令显示的是当时登录系统后执行的命令记录,而不是/home/testsys/cmd.hist文件里的命令记录。
但在/etc/profile 文件里加入 /home/testsys/cmd.hist 在第三次登录后,执行history命令才会显示/home/testsys/cmd.hist 文件里的命令记录,但也会显示当前登录后执行的命令记录,而/home/testsys/cmd.hist文件里的命令记录是固定的,不会加入当前登录所执行的命令。
请问:
1.设置HISTFILE环境变量是不是要重新登录后,history才能读取其指定的命令历史记录?这样的话,重新登录后,HISTFILE环境变量的值又变了,必须在/etc/profile文件里设置?这样很麻烦?

具体你可以帮忙测试一下就知道了。
__________
麻烦能帮忙解答一下history命令及HISTFILE环境变量具体的作用和工作原理吗?
待复,感谢!

------解决方案--------------------
history 一般是builtin command,不同shell的实现略有不同
你所希望的设置HISTFILE 就立刻可以看到file里面的所有command 有些shell比如ksh就是支持的
而另外一些shell比如bash是在shell start的时候读取的,之后设置是不起作用的
所以可以肯定你用的至少不是ksh

即使是对于bash这样的,也有变通的做法,可以使用内置的带参数 history 命令来强迫从最新设置的HISTFILE里面来读取,比如 history -r, 或者强迫当前session的history写入最新设置的HISTFILE里面 (有些shell为了performance的原因可能采用缓冲写,所以不是所有的cmd 即时反应在file里面,但通常logout会做flush)

楼主多参看man,自然有变通之道

比如 bash

man bash

       history -s arg [arg ...]
              With no options, display the command history list with line numbers.  Lines listed with a * have been modified.  An argument of n lists only  the
              last  n lines.  If the shell variable HISTTIMEFORMAT is set and not null, it is used as a format string for strftime(3) to display the time stamp
              associated with each displayed history entry.  No intervening blank is printed between the formatted time stamp and the history line.   If  file‐
              name  is  supplied,  it is used as the name of the history file; if not, the value of HISTFILE is used.  Options, if supplied, have the following
              meanings:
              -c     Clear the history list by deleting all the entries.
              -d offset
                     Delete the history entry at position offset.
              -a     Append the ``new'' history lines (history lines entered since the beginning of the current bash session) to the history file.