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

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

 xdg-open filename 

但我想知道如何才能通过输入以下内容从默认应用程序中的当前目录中打开文件:

 filename 

当然是Enter ,然后是Enter 。 而已。

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

更好的是,因为它不依赖于command-not-found包,所以(重新)实现Bash builtin command_not_found_handle来执行xdg-open如果$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 } 

好问题,漂亮的function。


仔细考虑一下:你可能不像你想的那样喜欢这个function,除非你也扩展了bash_completion处理程序。 想象一下想要打开file-with-a-long-name.txt ,然后设置

 alias o='xdg-open' 

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

 o f 

虽然输入完整的文件名需要繁琐的26 – 而且不包括对不可避免的错别字的退避。