I was wondering if there is any “clean” way to parse a variable containing whitespaces and quotes to cp or mv in bash.
Let’s say, we have a directory “test test” and want to move it into a directory “test2” from the same folder. But the “test test” is saved in a variable $fname.
If I now try something like
Running which leads to the desired result.
My “dirty” solution to the whole problem is then
#!/bin/bash
echo "#!/bin/bash">runtest2.sh
chmod 755 runtest2.sh
fname='test test.D'
echo "cp -R '$fname' test2">>runtest2.sh
#echo the command into a new script
#there it will appear as "cp -R 'test test' test2"
./runtest2.sh
Which works (of course, the real problem does not contain one file with a known name but multiple file names stored in a file); but I wonder whether there is a “cleaner” solution for this not including creating and executing of a second script.
Does anyone have an idea?
Hope that helps. Basically, use double-quotes so that you can get your
variable interpolation without string-concatenating single-quotes to the
whole thing which is messing you up. You may not need the braces around
the variable name, but it’s good practice regardless.
–
Good luck.
If you find this post helpful and are logged into the web interface,
show your appreciation and click on the star below…
I always use a while loop and read to get file names. If you use any search engine, you’ll find a lot about while loops in bash dealing with file names. Here is 1 example about globbing, special characters (like 2 dashes at beginning of file names) and read command in a while loop to process a list of file names: http://unix.stackexchange.com/questions/9496/looping-through-files-with-spaces-in-the-names
Thank you for additional info. I was already using while and read in the full version of my “dirty” solution at the moment I posted the thread, but I was just curious why I could not use cp or mv directly.