#!/bin/bash # Run a program from a given directory which is specified last on the command # line, stripping the directory using dirname a given number of times. # This is a hack to allow gqview to launch things such as an rxvt in a given # directory, since gqview doesn't support parameter expansion for its helper # programs. # # Also expands certain escape codes in the arguments to the command. # # for example, in the GQview configuration under the Editors tab: # 4 rxvt cdrun 1 rxvt # will run rxvt in the current image's directory. # # 7 dir gvim cdrun 1 gvim --remote-send ':cd %e' # # written by Steven Mueller # Created: Thursday January 03, 2002 # Last Modified: Friday January 04, 2002 00:50 PST if [ $# -lt 2 ]; then echo "Usage: $0 [n] program args .. dir" echo "Strips the last n elements off the pathname in dir, cd's there, and runs program args." echo "Escape codes: %d - the stripped directory argument" echo " %e - stripped dir with spaces preceeded by backslashes" echo " %f - the unstripped directory (file argument)" echo " %% - literal percent sign" exit 0 fi STRIP="$1" # if the first argument is a number, use it as the dirpart strip amount if expr "$STRIP" : '[0-9]*$' > /dev/null; then shift else STRIP=0 fi RUNPROG="$1" shift if ! which "$RUNPROG" > /dev/null; then echo "Error: $RUNPROG is not executable and is not found in the path. Aborting." 1>&2 exit 1 fi if [ x`which "$RUNPROG"` = x"$RUNPROG" ]; then # must do some relative path translation (cd `dirname "$RUNPROG`; RUNPROG="`pwd`/`basename "$RUNPROG"`") fi # Extract the directory argument -- the last one on the command line eval DIRARG=\"\${$#}\" # stripdirs dir n - strip n trailing pathname parts from dir stripdirs () { local dir=$1 for ((i = 0; i<$2; i++)); do dir=`dirname "$dir"` done echo "$dir" } set -e DIR=`stripdirs "$DIRARG" $STRIP` ESCDIR=`echo "$DIR" | perl -p -e 's, ,\\\\\\\\ ,g'` if ! cd "$DIR"; then echo "Error: Could not cd to $DIR, aborting" 1>&2 exit 1 fi # Substitute the patterns in the arguments scansubst () { echo "$1" | perl -p -e "s,%d,$DIR,g" \ | perl -p -e "s,%e,$ESCDIR,g" \ | perl -p -e "s,%f,$DIRARG,g" \ | perl -p -e "s,%%,%,g" } declare -a args i=0 while [ $# -gt 1 ]; do args[$i]=`scansubst "$1"` shift ((i++)) done exec $RUNPROG "${args[@]}"