简体   繁体   中英

Using history command in Bash alias

So I'm quite unfamiliar with Bash and am learning as I go along through trial and error. I'm wondering why the following doesn't work:

I define the function repeat in my bashrc file.

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). 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. 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:

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:

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. 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. 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 ". Bash manual gives an example for this.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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