![還記得資料夾中的「本地」bash 歷史記錄嗎?](https://rvso.com/image/97254/%E9%82%84%E8%A8%98%E5%BE%97%E8%B3%87%E6%96%99%E5%A4%BE%E4%B8%AD%E7%9A%84%E3%80%8C%E6%9C%AC%E5%9C%B0%E3%80%8Dbash%20%E6%AD%B7%E5%8F%B2%E8%A8%98%E9%8C%84%E5%97%8E%EF%BC%9F.png)
我在一個資料夾中有一個腳本,我使用長參數。我是否有機會獲得在該特定目錄中執行的命令的歷史記錄,而不是返回整個歷史記錄?
答案1
透過掛鉤 bash 的 PROMPT_COMMAND,每次收到新提示時都會執行此函數,因此這是檢查您是否位於想要自訂歷史記錄的目錄中的好時機。此函數有四個主要分支:
- 如果目前目錄 (
$PWD
) 沒有更改,則不執行任何操作(返回)。
如果殘疾人士有更改,然後我們設定一個本地函數,其唯一目的是將“自訂目錄”程式碼分解到一個地方。您需要將我的測試目錄替換為您自己的測試目錄(以 分隔|
)。
- 如果我們沒有更改為自訂目錄或更改為自訂目錄,則只需更新“上一個目錄”變數並從函數中返回即可。
由於我們已經更改了目錄,因此更新「上一個目錄」變量,然後將記憶體中的歷史記錄儲存到 HISTFILE 中,然後清除記憶體中的歷史記錄。
如果我們改變了進入自訂目錄,然後將 HISTFILE 設定為
.bash_history
目前目錄中的檔案。不然我們都變了在......之外自訂目錄,因此將 HISTFILE 重設為庫存目錄。
最後,由於我們更改了歷史文件,請讀回先前的歷史記錄。
為了讓事情順利進行,腳本設定 PROMPT_COMMAND 值並保存兩個內部使用變數(庫存 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
或者,如果您想安裝哦我的zsh,您可以添加歷史資料庫外掛程式並編寫一個自訂查詢來查詢 histdb 新增的 sqlite 資料庫。開發日記郵政。檢查獎勵命令部分。
查詢看起來像這樣
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
當我需要多次使用帶有長參數的命令時,我通常會在 my 中建立一個別名,或者如果您願意,~/.bash_aliases
也可以將其放入 your 中。~/.bashrc
這很簡單並且節省時間,而不是尋找歷史中的舊命令。