Allison Kaptur

An occasional blog on programming

Some Wacky Shell Scripting

I’m currently digging into the source of virtualenv, a python utility for managing environments. It’s incredibly handy, and I’d been using it for a while without really understanding how it worked. I’ll have more later on the details, but in the meantime, I hit a particularly puzzling bit of code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if [ -z "$VIRTUAL_ENV_DISABLE_PROMPT" ] ; then
    _OLD_VIRTUAL_PS1="$PS1"
    if [ "x" != x ] ; then
        PS1="$PS1"
    else
    if [ "`basename \"$VIRTUAL_ENV\"`" = "__" ] ; then
        # special case for Aspen magic directories
        # see http://www.zetadev.com/software/aspen/
        PS1="[`basename \`dirname \"$VIRTUAL_ENV\"\``] $PS1"
    else
        PS1="(`basename \"$VIRTUAL_ENV\"`)$PS1"
    fi
    fi
    export PS1
fi

This is largely intelligible – clearly we’re modifying the $PS1 variable, which sets the bash prompt. But what on earth is this line?

1
2
if [ "x" != x ] ; then
    PS1="$PS1"

x is not a variable defined elsewhere in the script, and bash will interpret both "x" and x as string literals anyway. Is there some bizarre shell in which this test can possibly return true?

As it turns out, there isn’t. The reason this code looks so bizarre is that it’s automatically generated by virtualenv. The original line of code is this:

1
2
if [ "x__VIRTUAL_PROMPT__" != x ] ; then
    PS1="__VIRTUAL_PROMPT__$PS1"

And then elsewhere we find its complement:

1
    content = content.replace('__VIRTUAL_PROMPT__', prompt or '')

Together, this code is entirely reasonable.

Thanks to user ruakh on Stack Overflow for the key insight here.