繁体   English   中英

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

[英]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.

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