Re: Solution [was Re: New Quiz: "What does this code do?" (3-Jan-2006)]
Ron Isaacson <Ron.Isaacson-/PgpppG8B+R7qynMiXIxWgC/[email protected]> Sun, 08 Jan 2006 00:31:59 -0500
| Newsgroups | gmane.comp.lang.perl.qotw.discuss |
|---|---|
| Message-ID | <[email protected]> |
Aaron Crane wrote:
>
> Shlomi Fish writes:
> > perl ~/bin/prompt-cmd.pl "$(pwd)" "\$trunk=$trunk" "\$base=$base" "~=$HOME"
> >
> > ~/bin/prompt-cmd.pl is this script, and as you can see it translates the
> > current working directory into something managable like:
> >
> > $trunk/modules/Test-Shlomif-Harness
>
> I can see how that would be handy.
>
> I'd have written the program something like this, expressing the string
> processing logic with a regex substitution rather than with substr and
> explicit conditions:
Interesting indeed! As long as we're on the subject of alternate
implementations though -- spawning a perl process every time bash
wants to print a prompt is a bit heavyweight. You can actually do this
entirely in a shell function:
curdir() {
typeset -a DIRVARS=(trunk base)
typeset CURDIR=$PWD
for DIRVAR in ${DIRVARS[*]}; do
typeset DIR=$(eval "echo \$$DIRVAR")
if [[ $CURDIR == $DIR || $CURDIR == $DIR/* ]]; then
CURDIR=\$$DIRVAR${CURDIR#$DIR}
fi
done
CURDIR=${CURDIR/#$HOME/~}
echo $CURDIR
}
PS1="(\u@\h) \$(curdir): "
One enhancement would be to automatically sort the DIRVARS list so the
longest paths are at the front, in case one is a prefix of another.
Sadly though, bash doesn't expose a sort builtin. If there were a
bash-qotw list, I might propose implementing various sort algorithms
using only shell builtins. :-)
BTW, I like that the path displayed in the prompt is something that
expands to the actual path. I often want a second (window/screen/etc.)
in the directory I'm working in; it's nice that the abbreviated path
is still something you can copy and type "cd <paste>" to get back to
the same place.
--
Ron Isaacson
Morgan Stanley
ron.isaacson-/PgpppG8B+R7qynMiXIxWgC/[email protected] / (212) 276-0268
NOTICE: If received in error, please destroy and notify sender. Sender
does not waive confidentiality or privilege, and use is prohibited.