在 shell 中,有没有办法让 运行 成为一个默认命令,当你只按回车而不输入任何内容时

In shell, is there a way to run a default command when you just press enter without entering anything

我认为当您在命令行上按回车键而不输入任何内容时,如果有一些东西 运行 会很酷。这是一种不寻常的事情,所以我不确定去哪里寻找以及如何接近它。

你知道我怎么能做那样的事吗?也许 运行 提示中有一些东西......但只有在没有输入任何内容时。

希望有人有想法或者知道。我个人使用 fish,但我会对任何主流 shell 感到好奇,bash、zsh.

谢谢!

P.S。或者,有没有办法在您输入搜索字符串的地方制作像 ctrl-R 这样的工具。你能给 ctrl-something 添加一个钩子吗?

您可以设置 "PS1" 或 "PROMPT_COMMAND" shell 变量来实现您想要的效果。

例如,我在我的 .bashrc 中设置 PS1 来控制我的提示:

export PS1='`date +%H:%M:%S` `echo $PWD | sed "s@$HOME@~@"` -> '

显示当前时间,然后是当前目录(去掉 HOME 部分),然后是“->”。

当我点击 return 时,它会更新时间:

10:50:19 ~ -> cd /tmp    # cd changes the date & directory part in prompt
10:50:51 /tmp ->         # I just hit return key
10:50:52 /tmp ->         # Now the prompt shows updated date

在 fish 中,您可以通过为 return 设置自定义绑定来做到这一点,如果它是空的,它会修改命令行:

function replace_command
    string length --quiet (commandline)
    or commandline "echo hello world"
    commandline -f execute
end

bind \n replace_command
bind \r replace_command

如果您在空命令行中按 return,这将 运行 echo hello world

(如果您不确定 bind 语句应该放在哪里,请查找 fish_user_key_bindings)。