Smart Complete in Bash

Recipe # | posted in Howto, Linux | Comments

1 – Problem Description

If you want to autocomplete shell commands, with up-arrow, by looking at the history of similar executed commands…plus some extra tweaking, keep reading.

2 – Solution

Add to your .bashrc file the following lines

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Autocomplete with up-arrow
# To avoid bind warning  on remote pcs
case "$TERM" in
xterm*|rxvt*)
bind '"\e[A":history-search-backward'
bind '"\e[B":history-search-forward'
;;
esac
#see: http://aplawrence.com/Linux/bash_history.html

# … and keep multi line commands together
shopt -s cmdhist

#Real-time history export amongst bash terminal windows (stackoverflow)
export HISTCONTROL=ignoredups:erasedups  # no duplicate entries
export HISTSIZE=100000                   # big big history
export HISTFILESIZE=100000               # big big history
shopt -s histappend                      # append to history, don't overwrite it

# Save and reload the history after each command finishes
#export PROMPT_COMMAND="history -n; history -a; history -c; history -r; $PROMPT_COMMAND"
export PROMPT_COMMAND="history -n; history -w; history -c; history -r; $PROMPT_COMMAND"

# Please be very careful with CTRL-s. On many terminals it stops the output 
# and your session will appear to be frozen! If that happens, use CTRL-q to 
# unfreeze it. You may want to remove CTRL+s mapping from your terminal altogether. 
# Add "stty stop ''" to your shell startup file (.bashrc for bash, .kshrc for ksh, etc).
stty stop ''

If you don’t have a .bashrc file, you can create it by typing in a linux shell

1
2
cd
vi .bashrc

Then copy-paste the above snippet add press :w and then ENTER to save the file.

Finally, source your .bashrc file in order to see the results ;)

1
source .bashrc

Comments