On Thu, 28 Feb 2008, Brock Noland wrote:

> Note the missing colon in the second example:
> [noland at a90 ~]$ ./mike.sh
> ./mike.sh: line 3: 0: %/*: syntax error: operand expected (error token is "%/*")
> EXEC_DIR =
> --------------
> EXEC_DIR = .
> [noland at a90 ~]$ cat mike.sh
> #!/bin/bash
> case $0 in
> */*) EXEC_DIR=${0:%/*} ;;
> *) EXEC_DIR=$PWD ;;
> esac
> echo EXEC_DIR = $EXEC_DIR
> echo '--------------'
> case $0 in
> */*) EXEC_DIR=${0%/*} ;;
> *) EXEC_DIR=$PWD ;;
> esac
> echo EXEC_DIR = $EXEC_DIR
>
> This is using parameter substitution.
>
> http://tldp.org/LDP/abs/html/parameter-substitution.html


Thanks Brock!  In other words, the problem with the script was that there 
was a single colon where it didn't belong.  I've tested the following 
script and it seems that this will do what we want:

case "$0" in
     */*) EXEC_DIR="${0%/*}" ;;
     *) EXEC_DIR="$PWD" ;;
esac

EXEC_DIR="$(builtin cd "$EXEC_DIR" && builtin echo "$PWD")"
builtin echo "$EXEC_DIR"


I think that is probably the best we've found so far (even though I don't 
completely understand it!).  It uses no external commands.  The command 
"builtin" forces the command that follows to be the shell builtin rather 
than an alias or external command.  I'm not sure that that trick is needed 
but I think it can't hurt.

I'm not sure that it handles every kind of special character, but I have 
tested it with a newline and spaces in the path and it worked fine.

Mike