Up Arrow + Enter替代运行上一个命令?

时间:2010-09-17 22:08:01

标签: linux unix shell

有时我必须连续多次运行命令,例如查看服务是否已启动,将手移离正常输入位置以反复按向上箭头和输入键变得乏味。有没有办法在没有Up Arrow和Enter键的情况下运行上一个命令,可能还有一个精心设计的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

理想情况下,我有这个脚本的别名,所以我可以在命令行中键入类似“prev”的内容,然后按Enter键再次运行上一个命令。

7 个答案:

答案 0 :(得分:18)

在bash中,您可以按 ctrl p 转到上一个命令 - 这比必须移动到箭头键要好得多。

另请参阅:https://github.com/fliptheweb/bash-shortcuts-cheat-sheet/

答案 1 :(得分:7)

使用

!!

运行上一个命令。

sudo !!

也适用于记录。

答案 2 :(得分:4)

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

watch command

答案 3 :(得分:3)

我经常在bash中使用“历史扩展”功能(通常使用 cntl R 激活) - 它以交互方式搜索您的历史记录以查找上一个最接近的匹配。< / p>

请参阅bash手册部分Searching for Commands in the History以及Using History Interactively

答案 4 :(得分: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的建议;我经常使用它。

答案 5 :(得分:2)

您是emacs还是vi用户?你可以使用

set -o vi 
set -o emacs

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

否则,你可以使用!!正如别人建议的那样。

答案 6 :(得分:1)

根据您正在使用的终端,我知道很多人都习惯将F3作为重复选项,但除非您有一个特殊的键盘以及更多可访问的功能键,否则它仍然在正常的输入范围之外。< / p>

我的键盘使功能键易于访问,但我不再在unix中执行太多的命令行工作,所以我无法确定是否仍然可以使用。