Shell Tricks: halp – a universal help tool

[Tweet : ADN : nvALT]

I have a lot of aliases and functions in my terminal, in addition to the plethora of UNIX commands. If I’m not sure what the source of a command is, getting info on it can require multiple tries. First a man check, then a type or alias command to see if it’s custom, then a man -k to see if I misspelled something, and so on. I eventually decided to just write an automated way to sift through those possibilities.

The function below will simply check if the command exists, then flip through “file,” “function,” and “alias” to see what kind it is, displaying the man page, typing out the function, or showing the alias depending on the result. It really just combines the man and type functionality into one command.

The only switch is -k, which will show the results of man -k if no matching command is found.

# A little helper for man/alias/function info
halp() {
	local YELLOW="\033[0;33m" DEFAULT="\033[0;39m"
	local apro=0 helpstring="Usage: halp COMMAND"

	while getopts "kh" opt; do
		case $opt in
			k) apro=1 ;;
			h) echo -e $helpstring; return;;
			*) return 1;;
	shift $((OPTIND-1))

	if [ $# -ne 1 ]; then
		echo -e $helpstring
		return 1

	local helpresult cmd=$1
	local cmdtest=$(type -t ${cmd})

	if [ -z "$cmdtest" ]; then
		echo -e "${YELLOW}Not a command$DEFAULT"
		if [[ $apro == 1 ]]; then
			man -k $cmd
			return 1

	if [[ $cmdtest == "file" ]]; then
		man $cmd
	elif [[ $cmdtest == "alias" ]]; then
		echo -ne "$YELLOW$cmd is an alias:  $DEFAULT"
		alias ${cmd}|sed -E "s/alias $cmd='(.*)'/\1/"
	elif [[ $cmdtest == "function" ]]; then
		echo -e "$YELLOW$cmd is a function:  $DEFAULT"
		type $cmd | tail -n +2

I have this running with a modified version of bash-completion that scopes in the halp command for tab-completing command names. Easy hack, so I won’t elaborate on that.

My where? tool is also a handy companion to this if you have enough custom scripts and sourced files to make it useful.

Ryan Irelan has produced a series of shell trick videos based on posts. Readers can get 10% off using the coupon code TERPSTRA.