简体   繁体   English

在 Bash 别名中使用 history 命令

[英]Using history command in Bash alias

So I'm quite unfamiliar with Bash and am learning as I go along through trial and error.所以我对 Bash 非常陌生,并且正在通过反复试验学习 go。 I'm wondering why the following doesn't work:我想知道为什么以下内容不起作用:

I define the function repeat in my bashrc file.我在我的 bashrc 文件中定义了 function repeat

repeat () {
         history > /dev/null
         !-2
}

And then call it in the same file as follows:然后在同一个文件中调用它,如下所示:

alias .="repeat"

Yes, I know I'm hijacking the dot operator but I have my own alias for it (specifically for sourcing ~/.bashrc).是的,我知道我正在劫持点运算符,但我有自己的别名(专门用于采购 ~/.bashrc)。 The idea is to be able to write .想法是能写. and have it repeat the last command.并让它重复最后一个命令。 This works if I type the commands manually in an interactive shell but doesn't work like this inside of an alias.如果我在交互式 shell 中手动键入命令,则此方法有效,但在别名中无法像这样工作。 Never mind that it's not repeatable more than once, I just want to get it working before I address that issue.不要介意它不能重复多次,我只想在解决该问题之前让它工作。 When I type .当我打字时. I get the following output:我得到以下 output:

bash: :-2: command not found

I considered that history is not reading from my history file when called non-interactively and contains no commands in its history, but no, this outputs my history:我认为history在非交互调用时不会从我的历史文件中读取,并且在其历史中不包含任何命令,但是不,这会输出我的历史:

repeat () {
        history
        !-2
}

However, I get the same result.但是,我得到了相同的结果。 The !! command doesn't seem to work.命令似乎不起作用。

Any idea what I'm doing wrong?知道我做错了什么吗?

EDIT: I have it working the way I want it now (please tell me if there is a more elegant solution) but I want to get rid of the command to be executed, ie I just want the output from the command itself.编辑:我现在按照我想要的方式工作(请告诉我是否有更优雅的解决方案)但我想摆脱要执行的命令,即我只想要命令本身的 output。 I thought I would try something like this:我想我会尝试这样的事情:

 19 repeat () {
 20         for ((i = 0; i<${1}; i++ ))
 21         do
 22                 $(fc -s) | tail -n +2
 23         done
 24 }
 25
 26 alias .="repeat 1"
 27 alias 1.="repeat 1"
 28 alias 2.="repeat 2"
 29 alias 3.="repeat 3"
 30 alias 4.="repeat 4"
 31 alias 5.="repeat 5"
 32 alias 6.="repeat 6"
 33 alias 7.="repeat 7"
 34 alias 8.="repeat 8"
 35 alias 9.="repeat 9"
 36 alias 10.="repeat 10"

But it unfortunately doesn't work, it gives me the wrong output and then when I try again it enters an infinite loop.但不幸的是它不起作用,它给了我错误的 output 然后当我再次尝试时它进入了无限循环。 How do I achieve this?我如何实现这一目标?

You can use the fc command which " is used to list or edit and re-execute commands from the history list ".您可以使用fc命令,该命令“用于列出或编辑并重新执行历史列表中的命令”。 Bash manual gives an example for this. Bash手册对此给出了一个例子。

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.一个有用的别名是r="fc -s" ,因此键入r cc运行以cc开头的最后一个命令,键入r重新执行最后一个命令。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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