Say I have several variables in a shell script (e.g. in zsh):
FOLDER_1, FOLDER_2, etc.
These variables refer to folders descending from /
. For example, if I have a path /home/me/stuff/items
the variables would be:
FOLDER_1='home'
FOLDER_2='me'
FOLDER_3='stuff'
Now, say that I want to build back the corresponding path by concatenating the variables. One possible way is to build the path as follows:
PATH=$FOLDER_1/$FOLDER_2/$FOLDER_3/
However, say that some of the variables FOLDER_i
come with trailing forward slashes, while others don't (and we don't know which) e.g.
FOLDER_1='home'
FOLDER_2='stuff/'
FOLDER_3='items'
My question is: How could I build the path robustly? (e.g. avoiding double slashes, and adding them where they need to be).
I thought one way to do this is to add the /
always between pairs of variables, and then delete any duplicates with sed
, but I can't make it to work (I am not sure I am handling /
correctly in sed
).
Also, am I reinventing the wheel? (i.e. is there any built-in that does this already?).
Finallly, if the variables are in an array, e.g. FOLDERS
, would it be possible to do this without looping? (or alternatively, by looping but without knowing how many FOLDERS
there are in the array).
%
method works for the single trailing slash mentioned in the queston. To cater for when there are multiple slashes,${parts[@]%%/*}
works. Here is a link to a bit more info on the slash issue: What do double slashes mean in UNIX path? Is 'cd dir/subdir// valid... – Peter.O Oct 24 '11 at 20:49/*
in this case does not mean zero or more slashes, but rather a slash followed by any number of characters. That means if your path starts with a slash, the result will be the empty string! – l0b0 Oct 25 '11 at 09:13extglob
(with regex) can by used..shopt -s extglob; ${parts[@]%%/+(/)}
... – Peter.O Oct 26 '11 at 02:54printf
command is also stored in a variable? I think that this would be useful to quite a few people reading this answer. – Leonid Apr 28 '23 at 10:50