Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Unix read a path name with two consecutive slashes? (e.g. /home/user//mystuff)

Here's the reason why I'm asking this question: I write a lot of bash and Perl scripts, and I find myself having to concatenate two paths every so often. Something like this is typical:

my $prefix = "/home/user/";
my $suffix = "/mystuff";
...
chdir $prefix.$suffix;

The problem is that I don't always remember if I put a slash at the end of the prefix, or if I put a slash at the beginning of the suffix. So I could accidentally concatenate two slashes together, like in the above example.

So my main question is whether or not two consecutive slashes will cause any problems and why. But also, do programmers have a convention for this? In the code that other people write, do directory names always end with a slash? It would be nice if there is some consistent rule that I could follow.

like image 298
HazySmoke Avatar asked Nov 05 '12 23:11

HazySmoke


2 Answers

It's perfectly fine. Repeated slashes are treated as one by Unix systems, so always add one.

my $prefix = "/home/user";  # Or "/home/user/"
my $suffix = "mystuff";
my $dir = "$prefix/$suffix";

But if you want a canonised path for whatever reason (e.g. it's going to be displayed to a user), you can use:

use Path::Class qw( dir );
my $prefix = dir("/home/user");  # Or "/home/user/"
my $dir = $prefix->subdir($suffix);
say $dir;

Whether you start with /home/user, /home/user/ or even ///home///user///, you end up with:

/home/user/mystuff
like image 168
ikegami Avatar answered Oct 25 '22 02:10

ikegami


Unix shells and kernels happily handle this, as well as things like "/firstpart/./secondpart", but generally you don't make trailing slash a part of the variable value to make path concatenation expressions look nicer: ${firstpart}/${secondpart} rather than ${firstpart}${secondpart}.

In scripts on Linux the readlink command line tool can be used to normalize file names.

like image 24
bobah Avatar answered Oct 25 '22 02:10

bobah