代码之家  ›  专栏  ›  技术社区  ›  Thomas

是否选择向上箭头+Enter以运行上一个命令?

  •  5
  • Thomas  · 技术社区  · 15 年前

    有时我必须连续运行一个命令很多次,例如查看服务是否已经启动,将我的手从正常的输入位置移开,反复按向上箭头和输入键会变得很麻烦。是否有一种方法可以运行前一个命令而不使用向上箭头和输入键,或者使用复杂的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 回复  |  直到 15 年前
        1
  •  3
  •   Roger Pate    15 年前

    在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的建议;我经常使用它。

        2
  •  16
  •   Mark Rushakoff    15 年前

    在巴什,你可以按 CTRL 转到上一个命令——这比移动到箭头键要好得多。

        3
  •  7
  •   Greg    15 年前

    使用

    !!

    运行上一个命令。

    sudo !!
    

    也可以,记录在案。

        4
  •  4
  •   dogbane    15 年前

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

    command

        5
  •  3
  •   Ether    15 年前

    我经常在bash中使用“历史扩展”功能(通常使用 睫状神经营养不良 R )--它以交互方式在历史记录中搜索上一个最近的匹配项。

    参见bash手册一节 Searching for Commands in the History 以及 Using History Interactively .

        6
  •  2
  •   Kizaru    15 年前

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

    set -o vi 
    set -o emacs
    

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

    否则,您可以使用!!就像别人建议的那样。

        7
  •  1
  •   Nathan Wheeler    15 年前

    根据你使用的终端,我知道很多时候f3是一个重复的选项,但这仍然超出了正常的打字范围,除非你有一个特殊的键盘,有更多的功能键。

    我的键盘使功能键很容易访问,但是我不再在Unix中做太多的命令行工作,所以我无法确定这是否仍然可行。