仅通过键入文件名从终端打开文件

Rad*_*anu 15 command-line bash gnome-terminal

我知道这xdg-open将从终端打开用户首选应用程序中的文件,如下所示:

xdg-open filename
Run Code Online (Sandbox Code Playgroud)

但我想知道如何仅通过键入以下内容在其默认应用程序中从当前目录打开文件:

filename
Run Code Online (Sandbox Code Playgroud)

其次是Enter,当然。而已。

zwe*_*ets 20

使用 Ubuntu 的command-not-found钩子,如Command Not Found Magic 中所指定。它目前用于建议要安装的软件包。请参阅/usr/share/doc/command-not-found/README您的系统上应安装哪个。

更好的是,因为它不依赖于command-not-found包,(重新)实现 Bash 内置command_not_found_handle来执行xdg-openif$1是一个现有文件,并将所有其他情况委托给以前的实现。

# Save the existing code for the handler as prev_command_not_found_handle.
# Bit of a hack, as we need to work around bash's lack of lexical closure,
# and cover the case when it is not defined at all.
eval "prev_$(declare -f command_not_found_handle)" >& /dev/null \
     || prev_command_not_found_handle () { 
            echo "$1: command not found" 1>&2
            return 127
        }

# Define the new implementation, delegating to prev_handler.
command_not_found_handle () {
    if [ -f "$1" ]; then
        xdg-open "$1"
    else
        prev_command_not_found_handle "$@"
    fi
}
Run Code Online (Sandbox Code Playgroud)

好问题,漂亮的功能。


再考虑一下:除非您还扩展了bash_completion处理程序,否则您可能不会像您想象的那样喜欢该功能。想象一下想要打开file-with-a-long-name.txt,然后设置

alias o='xdg-open'  
Run Code Online (Sandbox Code Playgroud)

将使(大约)四个按键就足够了:

o f<Tab><Enter>
Run Code Online (Sandbox Code Playgroud)

而输入完整的文件名需要繁琐的 26 - 这不包括不可避免的错别字的退格。