Clever Foo

Rafael Ferreira's life log

Archive for the ‘bash’ tag

Scriptfu: background a process and display spinner

without comments

I’m not sure why I’m particularly proud of this script snippet but since I couldn’t find anything similar on the web, I’ll post it here for posterity sake.

The snippet below runs a long running process (in this case a maven build) in the background while displaying a “spinner” animation to the user.

#!/usr/bin/env bash
build_async() {
	# checks if a pid is still running
	is_running() {
		kill -n 0 $1 &>/dev/null
		echo $?
	}
	retval() {
		wait $1
		echo $?
	}

	echo "Building "
	SPINNER='|/-\'
	echo -n "Running background build  "
	mvn -Dmaven.test.skip=true assembly:assembly &>/tmp/build.txt &
	PID=$!
	RUNNING=0

	# drawing the spinner:
	while [ $RUNNING == 0 ]
	do
		SPINNER="${SPINNER#?}${SPINNER%???}"
		printf '\b%.1s' "$SPINNER"
		sleep 1
		RUNNING=$(is_running $PID)
	done
	# making sure the background process worked
	if [[ $(retval $PID) == 1 ]]; then
		echo "ERROR: build failed, check /tmp/build.txt"
		exit 2
	fi

}

Written by raf

March 29th, 2010 at 11:44 am

Posted in General

Tagged with