Opening a file from terminal only by typing its name
Use Ubuntu's command-not-found
hook, as specified in Command Not Found Magic. It is currently used to suggest packages to install. Refer to /usr/share/doc/command-not-found/README
which should be installed on your system.
Better yet, because it does not depend on the command-not-found
package, (re)implement the Bash builtin command_not_found_handle
to do an xdg-open
if $1
is an existing file, and to delegate all other cases to the previous implementation.
# 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
}
Good question, nifty feature.
Thinking it over some more: you might not like the feature as much as you think, unless you also extend the bash_completion
handler. Imagine wanting to open file-with-a-long-name.txt
, then setting
alias o='xdg-open'
will make (about) four key presses suffice:
o f<Tab><Enter>
Whereas typing the full file name takes a tedious 26 - and that excludes backspacing over the inevitable typos.