Bash

bash,將參數傳遞給“歷史”命令

  • October 5, 2021

我執行以下操作以使歷史記錄更明智(即查看命令何時執行在故障排除時可能相當關鍵)

shopt -s histappend;   # Append commands to the bash history (~/.bash_history) instead of overwriting it   # https://www.digitalocean.com/community/tutorials/how-to-use-bash-history-commands-and-expansions-on-a-linux-vps
export PROMPT_COMMAND="history -a; history -c; history -r; $PROMPT_COMMAND"   # -a append immediately, then  -c clear history, then -r read history every time a prompt is shown instead of after closing the session.
export HISTTIMEFORMAT="%F %T  " HISTCONTROL=ignorespace:ignoreboth:erasedups HISTSIZE=1000000 HISTFILESIZE=1000000000   # make history very big and show date-time
alias h='history';   # Note: 'h 7' will show last 7 lines

這很好,但如果需要,我希望能夠獲得原始歷史輸出。這適用於ho(“歷史原創”),但我不能再做“ho 7”

alias ho="history | awk '{\$2=\$3=\"\"; print \$0}'" # 'history original'

所以我嘗試了以下方法,但失敗並出現錯誤:

function ho() { history $1 | awk '{\$2=\$3=\"\"; print \$0}'; } # 'history original'

如何創建允許我執行的別名或函式,ho 7而我只會看到最後 7 行?

您快到了。您正在定義一個函式,但使用alias關鍵字。只需刪除alias,你應該沒問題。接下來,您正在轉義 awk 變數,但您沒有雙引號,因此轉義被傳遞給awk. 這就是你所追求的:

ho() { history "$@" | awk '{$2=$3=""; print}'; }

通過“歷史原始”,我假設您的意思是您想要沒有時間戳的輸出。如果是這樣,只需設置HISTTIMEFORMAT為空history

HISTTIMEFORMAT= history

在別名中,

alias ho='HISTTIMEFORMAT= history'

引用自:https://unix.stackexchange.com/questions/671925