xbg (Source)

#!/bin/bash
##--------------------------------------------------------------------------##
#
#   Script: xbg
#   Author: Brian <genius@groupbcl.ca> :)
#   Date:   July 2001
#
#   Runs a process in the background
#
#   July 2002: added switch to change to a different desktop prior to
#   starting the program.
#
#   January 2008: Create output file in /tmp/xbg-out
#
#   September 2012: remove switch documented in July 2002 and add '-s' switch
#   to sleep for one second prior to starting the named command. Ensure the
#   named command exists prior to running it.
#
##--------------------------------------------------------------------------##
# BUUS: This script is part of Brian's Useful Utilities Set

function die {
    echo "xbg: $1" >&2
    exit 1
}

# Get some details out of the way first
[  "$1" ] || echo "usage: xbg [-s] program"

# Check for a switch; currently only '-s' (sleep for 1 second) is supported
SLEEP_SW=false
while [ x"$1" -a "$(expr substr "$1" 1 1)" = '-' ]
do
    SWITCH="${1#-}"
    [ $SWITCH = 's' ] && SLEEP_SW=true
    shift
done

# Ensure the program named in $1 exists and is executable
# (regexp extracts all text after the last '/')
XBG_PROGRAM=$(expr "$1" : '.*/\([^/]*\)$')
if [ "$XBG_PROGRAM" ]
then    # $1 contains '/': ensure it exists
    [ -f "$1" ] || die "$1: not found"
    [ -x "$1" ] || die "$1: not executable"
else
    which "$1" >/dev/null 2>&1
    [ $? != 0 ] && die "$1: not found in \$PATH"
fi

# Sleep for one second if requested by the user
$SLEEP_SW && sleep 1

# Get the basename
X=$(basename $1)
# Cut off the basename at the first "."
I=$(expr index $X ".")
[ $I -gt 0 ] && X=$(expr substr $X 1 $[I-1])

# Allocate a unique output file
if [ ! -d /tmp/xbg-out ]
then
    mkdir /tmp/xbg-out
    chmod a+rwx /tmp/xbg-out
fi
NUM=0
until [ ! -f $OUT_FILE ]
do
    NUM=$[NUM+1]
    OUT_FILE=/tmp/xbg-out/xbg.$X.$NUM.out
done

("$@" >$OUT_FILE 2>&1; sleep 60; rm $OUT_FILE) &
PID=$!
echo "$X started as PID $PID, output to $OUT_FILE"

# vim: tabstop=4