Reputation: 31
My script reads the name of folders in current directory:
for D in */ ; do
echo $D
done
The result is:
folder1/
folder2/
folder3/
But when I want to use $D like this:
mv *.zip /home/user/$D/zipfolder
it makes two /-s like /home/user/folder1//zipfolder and it fails
How do I remove the extra /?
Upvotes: 0
Views: 106
Reputation: 36229
for D in */
do
echo $D
ls /home/user/$D/zipfolder
done
The example with mv *.zip doesn't make much sense, since once the files are moved, why would you need a for-loop? So I changed the sample to something better reproducible.
Aaron made the suggestions I would have given, but since he didn't answer, and Kristianmitk's answer isn't satisfying, I repeat the comment as an answer.
a) Two slashes don't hurt.
ls a/b
ls a//b
ls a/./b
all evaluate to the same directory. This is handy in your case, since the slash is a natural terminator for the variable name
ls a/b/c
ls a/bb/c
ls a/bb/./c
D=bb/
ls a/$D/c
ls a/$D./c
Even the dot terminates a variable name, so the last line will work, too.
b) If you're irritated by two slashes, you may use curly braces, which is the canonical way, to isolate variable names from surrounding characters:
ls a/${D}c
or
for D in */
do
echo $D
ls /home/user/${D}zipfolder
done
Upvotes: 1
Reputation: 4778
If you are on bash version 4.2 or higher you can use ${D:0:-1}
as support for negative length was added.
If you are on an earlier version you would need to write ${D:0:${#D}-1}
But as suggested correctly in a comment below, it might be the case you don't have a slash as a last character, still with that solution above the last character will be removed...
If this is not acceptable, you might want to use ${D%/}
as nothing happens when the last character isn't a /
Upvotes: 1