jot*_*ttr 4 command-line bash logs command-history
假设我在命令行上发出一些命令:
#capture what follows
$ echo "foo"
foo
# don't capture
$ echo "bing"
bing
# capture again
$ echo "bar"
bar
Run Code Online (Sandbox Code Playgroud)
如何有选择地将命令记录到日志文件中,该文件只捕获在 cli 上发出的命令本身?即有效地实现类似于.bash_history, 但仅适用于某些命令:
$ cat command.log
echo "foo"
echo "bar"
Run Code Online (Sandbox Code Playgroud)
请注意,输出中,以STDOUT每个命令的应该不被记录。
我看过IO redirection,但找不到可行的解决方案。
最简单的方法是使用 bash 已经提供的功能。具体来说,HISTIGNORE变量:
HISTCONTROL
A colon-separated list of values controlling how commands are
saved on the history list. If the list of values includes
ignorespace, lines which begin with a space character are not
saved in the history list.
Run Code Online (Sandbox Code Playgroud)
所以,你可以做一些简单的事情
$ HISTCONTROL=ignorespace
Run Code Online (Sandbox Code Playgroud)
然后,您输入的任何带前导空格的命令都将被忽略:
HISTCONTROL=ignorespace
$ history -c ## clear previous history for this session
$ echo foo
foo
$ echo bar
bar
$ history
1 echo foo
2 history
Run Code Online (Sandbox Code Playgroud)
正如你在上面看到的,以空格开头的命令被忽略了。
您还可以使用HISTIGNORE:
HISTCONTROL
A colon-separated list of values controlling how commands are
saved on the history list. If the list of values includes
ignorespace, lines which begin with a space character are not
saved in the history list.
Run Code Online (Sandbox Code Playgroud)
如果您设置HISTIGNORE为类似的内容#foo,然后将其附加到您想要忽略的命令,您可以获得相同的效果:
$ HISTIGNORE="*#foo"
$ history -c
$ echo foo
foo
$ echo "bar" #foo
bar
$ history
1 echo foo
2 history
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,如果要将其保存到文件中,只需运行history > file. 或者,将历史文件设置file为会话:
$ HISTFILE="/tmp/file"
$ HISTCONTROL=ignorespace
$ history -c
$ echo foo
foo
$ echo bar
bar
$ history -a ## write the session's history to $HISTFILE
$ cat /tmp/file
echo foo
history -a
Run Code Online (Sandbox Code Playgroud)