bash: smart autocomplete based on history?
Run in your bash:
cat >> ~/.inputrc <<'EOF'
"\e[A": history-search-backward
"\e[B": history-search-forward
EOF
Open a new shell session, or just reload inputrc:
bind -f ~/.inputrc
Now use ⬆ and ⬇ after entering the beginning of the command - it will auto-complete from history.
According to this page ("Turn on Bash Smart Completion") on Ubuntu Blog, it is as easy as editing your bash.bashrc
file. For clarity, I rewrote these instructions below in a more beginner-friendly manner.
Instructions (Linux)
-
From a terminal window, edit your system's
bash.bashrc
file. To do this with a command-line text editor like nano, execute the commandsudo nano /etc/bash.bashrc
(and if needed, enter your password). -
Use the arrow keys to find these lines:
#if [ -f /etc/bash_completion ]; then # . /etc/bash_completion #fi
-
Un-comment each of these lines (by removing the
#
prefix that each line has). -
Save the file (you do this in nano by pushing Ctrl+o and Enter, then Ctrl+x to quit), and it should now work. Please note: for the changes to take effect in existing terminals,
/etc/bash.bashrc
will need to be sourced. Alternatively, logout and login again, or just reboot.
To disable it, all you need to do is re-comment each of the lines above (by adding a #
to the start of each line).
Presumably, the above will also work (for your user account)
if you insert the above three lines, minus their #
characters,
into your personal .bashrc
file. If you do that,
you won't need to use sudo
.
According to this blog post ("Bash Completion for Mac OS X"), the instructions are different for Mac OS X. Here is what you need to do.
Instructions (Mac OS X)
-
Make sure you have Homebrew installed, and then use it to install the package
bash-completion
(by typing the commandbrew install bash-completion
). -
Homebrew should now tell you what you need to do to complete the installation. In this case, you need to add these three lines to your
.bashrc
file (using either a command-line text editor like nano which we used above, or a graphical one):if [ -f $(brew --prefix)/etc/bash_completion ]; then . $(brew --prefix)/etc/bash_completion fi
-
You should now have auto-completion in bash. Please note: for the changes to take effect in existing shells,
.bashrc
will need to be sourced. Alternatively, logout and login again, or just reboot.
To disable it, all you need to do is remove the lines we added above, and run the command brew uninstall bash-completion --force
.