Skip to content

Instantly share code, notes, and snippets.

@hansifer
Last active June 27, 2018 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hansifer/85757deea7f19bae51ef9e3919482fd7 to your computer and use it in GitHub Desktop.
Save hansifer/85757deea7f19bae51ef9e3919482fd7 to your computer and use it in GitHub Desktop.
searchable bash command history with results selection
function chop-first-column { awk '{for (i=2; i<NF; i++) printf $i " "; print $NF}' ; }
function strip-colors { sed "s/\x1B\[\([0-9]\{1,2\}\(;[0-9]\{1,2\}\)\?\)\?[mGK]//g" ; }
function h {
local cyan='\e[0;36m'
local cyan2='\e[1;36m'
local NC='\e[0m' # No Color
if [ $# -gt 0 ]; then
REGEXP="$1"
shift #ignore already-captured first arg
for var in "$@"
do
REGEXP="$REGEXP|$var"
done
IFS=$'\r\n'
ARR=($(history | sort -k2 | uniq -f2 | sort -n | chop-first-column | grep -v "^h\b" | egrep -i --color="always" "$REGEXP"))
ARR_SIZE=${#ARR[@]}
SIZE_LEN=${#ARR_SIZE} # eg, 514 -> 3
if [ $ARR_SIZE -gt 0 ]; then
echo;
local CNT=0
for var in "${ARR[@]}"
do
CNT=$(($CNT + 1))
printf " ${cyan}%${SIZE_LEN}s${NC} %s\n" "$CNT" "${var}"
done
printf " ${cyan}\n"
# read -n $SIZE_LEN -p " select a command: " num
read -p " select a command: " num
printf "${NC}\n"
CMD=$(printf "${ARR[$num - 1]}" | strip-colors)
if [ $num -ne 0 -o $num -eq 0 2>/dev/null ]; then
if [[ ($num -gt 0) && ($num -le $ARR_SIZE) ]]; then
printf " ${cyan2}$CMD${NC}\n\n"
eval "$CMD"
fi
fi
fi
else
history
fi
}
export -f h
@hansifer
Copy link
Author

hansifer commented Jun 27, 2018

h [SEARCH STRING]...

Select found command from results by number or press ENTER to ignore.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment