[英]Using history expansion in a bash alias or function
我想做一件簡單的事情讓我的隊友生活更輕松。 他們不斷地將報價復制到命令行中,這些命令行的格式化會破壞命令,即:“test”與“test”
事實證明,令人驚訝的是:
function damn() { !!:gs/“/" }
要么:
alias damn='!!:gs/“/"'
似乎都沒有工作,並一直給我錯誤
-bash: !!:gs/“/" : No such file or directory
要不就:
>
我必須在這里遺漏一些明顯的東西。
!
在函數或別名中不起作用。 根據bash手冊:
在讀取完整行之后 ,在shell將其分解為單詞之前立即執行歷史記錄擴展。
您可以使用builtin fc
命令:
[STEP 100] # echo $BASH_VERSION
4.4.19(1)-release
[STEP 101] # alias damn='fc -s “=\" ”=\" '
[STEP 102] # echo “test”
“test”
[STEP 103] # damn
echo "test"
test
[STEP 104] #
為了快速引用,以下是help fc
輸出。
fc: fc [-e ename] [-lnr] [first] [last] or fc -s [OLD=NEW] [command]
Display or execute commands from the history list.
fc is used to list or edit and re-execute commands from the history list.
FIRST and LAST can be numbers specifying the range, or FIRST can be a
string, which means the most recent command beginning with that
string.
Options:
-e ENAME select which editor to use. Default is FCEDIT, then EDITOR,
then vi
-l list lines instead of editing
-n omit line numbers when listing
-r reverse the order of the lines (newest listed first)
| With the `fc -s [OLD=NEW ...] [command]' format, COMMAND is
| re-executed after the substitution OLD=NEW is performed.
A useful alias to use with this is r='fc -s', so that typing `r cc'
runs the last command beginning with `cc' and typing `r' re-executes
the last command.
Exit Status:
Returns success or status of executed command; non-zero if an error occurs.
這是一個稍微更通用的解決方案,使用bash函數來包裝fc
調用,如果你想對字符串做一些超出替換的事情。
function damn() {
# Capture the previous command.
cmd=$(fc -ln -1)
# Do whatever you want with cmd here
cmd=$(echo $cmd | sed 's/[“”]/"/g')
# Re-run the command
eval $cmd
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.