コマンドライン入力をログファイルにキャプチャして同時に実行する方法は?

コマンドライン入力をログファイルにキャプチャして同時に実行する方法は?

コマンドラインでいくつかのコマンドを実行するとしましょう。

#capture what follows
$ echo "foo"
foo

# don't capture
$ echo "bing"
bing

# capture again
$ echo "bar"
bar

コマンドを記録する方法オプションでログファイルにただ捕獲注文するCLIに直接投稿しますか?つまり、次のようなものを効果的に実装し.bash_historyますが、特定のコマンドにのみ該当します。

$ cat command.log
echo "foo"
echo "bar"

気づく出力STDOUT各コマンドの to は次のようになります。いいえ記録されます。
私は見たことがないIOリダイレクトしかし、実行可能な解決策が見つかりません。

ベストアンサー1

最も簡単な方法は、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. 

だから簡単なことができます

$ HISTCONTROL=ignorespace

これにより、前にスペースを含むコマンドを入力すると無視されます。

HISTCONTROL=ignorespace
$ history -c            ## clear previous history for this session
$ echo foo
foo
$   echo bar
bar
$ history 
1  echo foo
2  history 

上記のように、スペースで始まるコマンドは無視されます。


以下も使用できますHISTIGNORE

    HISTIGNORE
          A colon-separated list of patterns used to decide which  command
          lines  should  be  saved  on  the history list.  Each pattern is
          anchored at the beginning of the line and must  match  the  com‐
          plete  line  (no  implicit  `*'  is  appended).  Each pattern is
          tested against the line after the checks specified  by  HISTCON‐
          TROL  are  applied.   In  addition  to  the normal shell pattern
          matching characters, `&' matches the previous history line.  `&'
          may  be  escaped  using  a  backslash;  the backslash is removed
          before attempting a match.  The second and subsequent lines of a
          multi-line compound command are not tested, and are added to the
          history regardless of the value of HISTIGNORE.

HISTIGNORE同様の値を設定して無視したいコマンドに追加すると、#foo同じ効果が得られます。

$ HISTIGNORE="*#foo"
$ history -c  
$ echo foo
foo
$ echo "bar" #foo
bar
$ history 
1  echo foo
2  history 

どちらの場合もファイルに保存するには、を実行します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

おすすめ記事