简体   繁体   English

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

[英]Using history expansion in a bash alias or function

I am trying to make a simple thing to make my teammates lives easier. 我想做一件简单的事情让我的队友生活更轻松。 They are constantly copying quote into the command line that are formatted which breaks the command ie: “test“ vs. "test" 他们不断地将报价复制到命令行中,这些命令行的格式化会破坏命令,即:“test”与“test”

It's proved surprisingly annoying to do with: 事实证明,令人惊讶的是:

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

or: 要么:

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

Neither seems to work and keeps giving me either the error 似乎都没有工作,并一直给我错误

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

or just: 要不就:

> >

I must be missing something obvious here. 我必须在这里遗漏一些明显的东西。

! does not work in functions or aliases. 在函数或别名中不起作用。 According to bash manual: 根据bash手册:

History expansion is performed immediately after a complete line is read , before the shell breaks it into words. 在读取完整行之后 ,在shell将其分解为单词之前立即执行历史记录扩展。

You can use the builtin fc command: 您可以使用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] #

For quick referecne, the following is output of help fc . 为了快速引用,以下是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.

Here is a slightly more general solution using a bash function to wrap the fc call, if you want to do something to the string beyond substitution. 这是一个稍微更通用的解决方案,使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM