フォルダー内の「ローカル」bash 履歴を覚えていますか?

フォルダー内の「ローカル」bash 履歴を覚えていますか?

長い引数を使用するスクリプトがフォルダー内にあります。履歴全体をさかのぼるのではなく、特定のディレクトリで実行されたコマンドの履歴を取得することはできますか?

答え1

bash の PROMPT_COMMAND にフックすると、新しいプロンプトが表示されるたびにこの関数が実行されるので、カスタム履歴が必要なディレクトリにいるかどうかを確認するのに適したタイミングになります。この関数には 4 つの主要なブランチがあります。

  1. 現在のディレクトリ ( $PWD) が変更されていない場合は、何もしません (戻ります)。

障害者の場合もっている変更したら、「カスタム ディレクトリ」コードを 1 か所にまとめるという目的のみを持つローカル関数を設定します。私のテスト ディレクトリを独自のものに置き換える必要があります ( で区切る|)。

  1. カスタム ディレクトリ内またはカスタム ディレクトリ外に変更していない場合は、単に「前のディレクトリ」変数を更新し、関数を終了します。

ディレクトリを変更したので、「前のディレクトリ」変数を更新し、メモリ内の履歴を HISTFILE に保存し、メモリ内の履歴をクリアします。

  1. もし私たちが変わったらの中へ.bash_historyカスタム ディレクトリの場合は、HISTFILE を現在のディレクトリ内のファイルに設定します。

  2. そうでなければ、私たちは変わったからカスタム ディレクトリなので、HISTFILE を標準のディレクトリにリセットします。

最後に、履歴ファイルを変更したので、以前の履歴を読み戻します。

処理を開始するために、スクリプトは PROMPT_COMMAND 値を設定し、2 つの内部使用変数 (標準の HISTFILE と「前のディレクトリ」) を保存します。

prompt_command() {
  # if PWD has not changed, just return
  [[ $PWD == $_cust_hist_opwd ]] && return

  function iscustom {
    # returns 'true' if the passed argument is a custom-history directory
    case "$1" in
      ( */tmp/faber/somedir | */tmp/faber/someotherdir ) return 0;;
      ( * ) return 1;;
    esac
  }

  # PWD changed, but it's not to or from a custom-history directory,
  # so update opwd and return
  if ! iscustom "$PWD" && ! iscustom "$_cust_hist_opwd"
  then
    _cust_hist_opwd=$PWD
    return
  fi

  # we've changed directories to and/or from a custom-history directory

  # save the new PWD
  _cust_hist_opwd=$PWD

  # save and then clear the old history
  history -a
  history -c

  # if we've changed into or out of a custom directory, set or reset HISTFILE appropriately
  if iscustom "$PWD"
  then
    HISTFILE=$PWD/.bash_history
  else
    HISTFILE=$_cust_hist_stock_histfile
  fi

  # pull back in the previous history
  history -r
}

PROMPT_COMMAND='prompt_command'
_cust_hist_stock_histfile=$HISTFILE
_cust_hist_opwd=$PWD

答え2

ジェフの答え単一のディレクトリの履歴が必要な場合は最適ですが、翻訳使える履歴ディレクトリごとすべてのディレクトリのディレクトリ固有の履歴を取得します。

zsh は次の方法でインストールできます。

brew install zsh

あるいは、インストールしたい場合はオーマイズッシュ、あなたは履歴データベースプラグインをインストールして、histdbが追加するsqlite dbを照会するカスタムクエリを作成します。それについて、および自動補完の追加について書きました。開発日記投稿を確認してくださいボーナスコマンドセクション。

クエリは次のようになります

show_local_history() {
    limit="${1:-10}"
    local query="
        select history.start_time, commands.argv 
        from history left join commands on history.command_id = commands.rowid
        left join places on history.place_id = places.rowid
        where places.dir LIKE '$(sql_escape $PWD)%'
        order by history.start_time desc
        limit $limit
    "
    results=$(_histdb_query "$query")
    echo "$results"
}

これもオプションの制限を受け入れます:

show_local_history 50

例えば。

答え3

長い引数を持つコマンドを何度も使用する必要がある場合、通常は にエイリアスを作成します。~/.bash_aliasesまたは、必要に応じて にエイリアスを配置することもできます~/.bashrc。これは簡単で、履歴で古いコマンドを探すよりも時間を節約できます。

関連情報