Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unix variable best practice: Should variable containing a path end in a slash

Tags:

path

unix

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.

like image 808
sixtyfootersdude Avatar asked Apr 22 '10 20:04

sixtyfootersdude


3 Answers

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.

like image 76
frankc Avatar answered Sep 22 '22 07:09

frankc


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.

like image 39
Andy Mortimer Avatar answered Sep 20 '22 07:09

Andy Mortimer


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.

like image 32
Kelly S. French Avatar answered Sep 18 '22 07:09

Kelly S. French