2010-09-17 47 views
5

有时我必须连续多次运行一个命令,例如,看看服务是否已经启动,并且将我的手从正常的输入位置移开以重复按向上箭头和回车键变得单调乏味。有没有办法在没有向上箭头键和回车键的情况下运行上一个命令,或许可以使用精心制作的shell脚本?向上箭头的替代方法+输入以运行上一个命令?

我试过以下,但它不令人满意,因为它不能执行别名,并且它有点慢。

history | tail -2 | head -1 | cut -d' ' -f4- | cat > prev_command.txt 
sleep .01 
chmod 777 prev_command.txt 
eval prev_command.txt 
rm prev_command.txt 

理想我有一个别名到这个脚本,所以我可以在输入类似的命令行“上一页”并按下回车键再次运行先前的命令。

+0

因此,输入“prev”比输入快吗? – halfdan 2010-09-17 22:11:56

+3

应该移至superuser.com – stepancheg 2010-09-18 00:14:38

回答

3

在bash:

 
$ help fc 
fc: fc [-e ename] [-lnr] [first] [last] or fc -s [pat=rep] [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 [pat=rep ...] [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. 

注意的建议别名R等我经常使用它。

15

在bash,你可以按CTRL p去前面的命令 - 这比其移动到方向键好多了。

+0

这也适用于'tcsh'。 – 2010-09-17 22:18:18

+0

在ksh和zsh中使用“r”也起作用。 – 2010-09-17 23:03:47

+4

如果你碰巧走得太远,可以循环回到下一个命令''ctrl + n''。 – davidjb 2014-04-03 01:40:55

1

根据您使用的是哪个终端,我知道很多人都习惯将F3作为重复选项,但这仍然超出了打字的正常范围,除非您有一个具有更多可访问功能键的特殊键盘。

我的键盘使得功能键可以轻松访问,但是我不再在unix中执行很多命令行工作,所以我无法确切地告诉您这是否仍然可行。

7

使用

!!

运行以前的命令。

sudo !! 

也适用于备案。

+0

有没有办法把!或者将下面答案中的ctrl p转换为别名?我尝试了别名l ='!!',但是当我运行它时,它给了我一个“bash:!!:command not found”的错误。 – Thomas 2010-09-17 22:57:27

4

而不是连续多次运行相同的命令,为什么不是watch呢? watch将反复运行指定的命令并在标准输出中显示输出,以便您可以看到它随时间而变化。

watchcommand

2

你是一个Emacs或vi用户?您可以使用

set -o vi 
set -o emacs 

来设置emacs或vi键绑定。然后,您可以在bash中使用emacs或vi键绑定。我不知道这是否适用于其他炮弹。我相信vi模式在插入模式下开始,所以你需要按esc进入命令模式。在emacs模式下(默认),你可以使用ctrl + p然后ctrl + j移动到前一行并执行回车。

否则,您可以使用!正如别人所说的那样。

相关问题