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/itemsthe 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).
Building paths robustly
shell script
You can use printf with an array:parts=($FOLDER_1 $FOLDER_2 $FOLDER_3);printf '/%s' ${parts[@]%/}# Use printf -v path to save it into a variable called path instead of printing itThe % operator trims trailing strings, in this case /. By applying it to parts[@], it trims each array member separately.The key to understanding this printf trick, is this bit from man 1 printf: The format string is reused as often as necessary to satisfy the arguments.