Wednesday, October 10, 2007

Unexepected side effects in shell scripts

Shell scripts that fail to preserve the expected environment are a waste of everyone's time. For instance, you call a function which changes the current directory to somewhere else for its own purposes but fails to change back on all exit paths from the function. Trying to remember which directory you might be in later on becomes combinatorially difficult as more conditional statements are added over time. To make it more concrete:

BAD:


function MyFunction() {
cd some_random_directory
# Do something useful
}


GOOD:


function MyFunction() {
# Change to the necessary directory
pushd some_random_directory

# Do something useful

# Now pop the directory off the stack
cd -

}


If you have conditional statements, then make sure you catch them too:

BAD:


function MyFunction() {
# Change to the necessary directory
pushd some_random_directory

# Do something useful and test something
if [ "${test}" == "value" ]; then
return # Oops, this function left us somewhere unexpected
fi

# Now pop the directory off the stack
cd -
}


GOOD:


function MyFunction() {
# Change to the necessary directory
pushd some_random_directory

# Do something useful and test something
if [ "${test}" == "value" ]; then
# Don't forget to pop the directory off the stack
cd -

return
fi

# Now pop the directory off the stack
cd -
}


Basically, preserve an expected and known state between function calls, just like any modern other programming language.

No comments: