Use Absolute Paths

As a guy who spent a few hours last week figuring out what was changing the permissions on / and /tmp on two of my servers, I offer this advice: always use absolute paths in scripts.

You can’t count on the path or current working directory to be what you want, especially if your script runs from cron. And if you can’t count on that you run the risk of changing the wrong permissions, filling the wrong filesystem, or just generally doing the wrong thing.

In my case a script changed the permissions of /tmp, using code very similar to:

cd /opt/application; chmod 700 tmp

What if the ‘cd’ fails? What will the chmod change? A better way to do that is:

/bin/chmod 700 /opt/application/tmp

Sometimes you just can’t use absolute paths, though. In that case I usually urge people to test the location first using “landmarks” that should be there already. For example, say your script makes a change to a web server. If you first test to make sure that “bin/apachectl” exists in the proper location relative to where you think you should be you’ll increase the chances of not doing something bad:

if [ ! -f "bin/apachectl" ]; then
echo "I'm not where I should be."
exit 1

I also usually suggest that if you pick up input from a program, like ‘/bin/pwd’, you check to make sure you got something back. What happens if:

PWD = `/bin/pwd`
/bin/chmod 700 $PWD/tmp

doesn’t end up having a value in $PWD?

Moral of the story is twofold: First, use absolute paths wherever possible. Second, always ask yourself what will happen if part of your script fails. Will it keep running and do the wrong thing, or will it detect the problem and handle it?

Comments on this entry are closed.

  • I like using set -e and things like trap cleanup_func EXIT – they can (and usually do) go a great way towards avoiding these things.

Previous Post:

Next Post:

%d bloggers like this: