tags:

views:

177

answers:

3

What is the best practice when storing a directory in a file name on a unix system? Should the directory path end in a slash?

Method A

TMP="/tmp/pasteTmp/"

which allows you to do:

cd "$TMP$fileName"

Method B

TMP="/tmp/pasteTmp"

which allows you to do (with an extra slash which seems less clean):

cd "$TMP/$fileName"

but also allows you to do:

cd "$TMP/actualFileName"

Which I think is impossible using the first method.

+9  A: 

it doesn't matter. Instead you should always assume the trailing slash is not there when using the path by adding your own. /foo// is equivalent to /foo/ so it works out.

frankc
If one thing does matter, it's to **be consistent** when you're the person doing the coding.
Kaleb Pederson
+2  A: 

When you refer to a directory in normal usage, you don't include the slash: my home directory is /home/andy, not /home/andy/. If you write scripts that assume the trailing slash is there, sooner or later you'll forget to include it and surprise yourself.

I'm not sure I agree with you that the extra slash "seems less clean". When you're not using variables you expect a slash to separate the directory and file names; when the directory name is stored in a shell variable, I still find it natural to read and write with the slash separating the parts.

Andy Mortimer
+2  A: 

When you work on a big monster application with 100's of scripts and lots of libraries and executables, you start to worry more about what causes less pain rather than what "seems less clean". I'd agree that the double slash looks funny but the reality is that Unix doesn't care. I'd rather assume the trailing slash isn't there and know it will still work when I add one myself than hope everyone remembered to include one and then my code breaks when someone else forgets about adding the trailing slash.

Put yourself in a situation where you are in control of whether your code will work. Depending on others to follow a convention leads to headaches and 3am support calls when they inevitably don't.

Kelly French
+1 for function over form
frankc