在bash别名或函数中使用历史扩展

时间:2018-02-09 00:20:48

标签: linux bash

我想做一件简单的事情让我的队友生活更轻松。他们不断地将报价复制到命令行中,这些命令行的格式化会破坏命令,即:“test”vs." test"

事实证明这令人非常恼火:

function damn() { !!:gs/“/" }

或:

alias damn='!!:gs/“/"'

两者似乎都没有用,并且一直给我错误

-bash: !!:gs/“/" : No such file or directory

或只是:

  

>

我必须在这里遗漏一些明显的东西。

2 个答案:

答案 0 :(得分:6)

fc在函数或别名中不起作用。根据bash手册:

  

历史记录扩展在读完整行后立即执行 ,然后将shell分解为单词。

您可以使用内置[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. 的输出。

push

答案 1 :(得分:1)

如果你想对字符串做一些超出替换的事情,这是一个稍微更通用的解决方案,使用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
}