Skip to content

Instantly share code, notes, and snippets.

@tsharley
Forked from jeandat/pre_post_hook_prompt.md
Last active January 25, 2024 13:51
Show Gist options
  • Select an option

  • Save tsharley/1cba00ee8ca648f3adeb51c94a0b741b to your computer and use it in GitHub Desktop.

Select an option

Save tsharley/1cba00ee8ca648f3adeb51c94a0b741b to your computer and use it in GitHub Desktop.
Bash pre- & post-command hooks

Bash pre- & post-command hooks

Explained here.

AT_PROMPT=1

function PreCommand() {
	# This will run before any command is executed.
	if [ -z "$AT_PROMPT" ]; then
		return
	fi
	unset AT_PROMPT
	# Do precommand stuff here.
	echo "Running PreCommand"
}

trap "PreCommand" DEBUG

FIRST_PROMPT=1


function PostCommand() {
	# This will run after the execution of the previous full command line.
	# The logic avoids executing it at the first prompt of a new shell.
	AT_PROMPT=1
	if [ -n "$FIRST_PROMPT" ]; then
		unset FIRST_PROMPT
		return
	fi
	# Do postcommand stuff here.
	echo "Running PostCommand"
}

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