#!/bin/bash # This script starts an instance of vncserver, runs a command # with that server available, and kills the X server when done. The return # value of the command becomes the return value of this script. set -e PROGNAME=vnc-run SERVERNUM=99 AUTHFILE= ERRORFILE=/dev/null STARTWAIT=3 VNCARGS="-screen 0 640x480x8" LISTENTCP="-nolisten tcp" XAUTHPROTO=. # Query the terminal to establish a default number of columns to use for # displaying messages to the user. This is used only as a fallback in the event # the COLUMNS variable is not set. ($COLUMNS can react to SIGWINCH while the # script is running, and this cannot, only being calculated once.) DEFCOLUMNS=$(stty size 2>/dev/null | awk '{print $2}') || true if ! expr "$DEFCOLUMNS" : "[[:digit:]]\+$" >/dev/null 2>&1; then DEFCOLUMNS=80 fi # Display a message, wrapping lines at the terminal width. message () { echo "$PROGNAME: $*" | fmt -t -w ${COLUMNS:-$DEFCOLUMNS} } # Display an error message. error () { message "error: $*" >&2 } # Display a usage message. usage () { if [ -n "$*" ]; then message "usage error: $*" fi cat <&2 exit 2 fi if ! which xauth >/dev/null; then error "xauth command not found" exit 3 fi if ! which vncserver >/dev/null; then error "vncserver command not found" exit 4 fi # If the user did not specify an X authorization file to use, set up a temporary # directory to house one. if [ -z "$AUTHFILE" ]; then VNC_RUN_TMPDIR="$(mktemp --directory --tmpdir $PROGNAME.XXXXXX)" AUTHFILE=$(mktemp -p "$VNC_RUN_TMPDIR" Xauthority.XXXXXX) fi # Start VNC. MCOOKIE=$(mcookie) XAUTHORITY=$AUTHFILE xauth source - << EOF >>"$ERRORFILE" 2>&1 add :$SERVERNUM $XAUTHPROTO $MCOOKIE EOF XAUTHORITY=$AUTHFILE vncserver ":$SERVERNUM" >>"$ERRORFILE" 2>&1 & VNCPID=$! sleep "$STARTWAIT" if ! wait ${VNCPID}; then exit 5 fi # Start the command and save its exit status. set +e DISPLAY=:$SERVERNUM XAUTHORITY=$AUTHFILE "$@" 2>&1 RETVAL=$? set -e # Kill VNC now that the command has exited. vncserver -kill ":$SERVERNUM" # Clean up. XAUTHORITY=$AUTHFILE xauth remove ":$SERVERNUM" >"$ERRORFILE" 2>&1 if [ -n "$VNC_RUN_TMPDIR" ]; then if ! rm -r "$VNC_RUN_TMPDIR"; then error "problem while cleaning up temporary directory" exit 5 fi fi # Return the executed command's exit status. exit $RETVAL