Tom Klino
Tom Klino

Reputation: 2504

Problems with variables with spaces

I wrote a small script that copies, then removes and then creates a symbolic link from where the file was moved to it's new location. To easly do it for multiple times I used variables, but when a file has spaces in it, I'm getting some errors, even though I'm using '\' in front of every space. Here is my code:

dest=~/Videos-win/file\ name\ with\ spaces
src=~/Downloads/file\ name\ with\ spaces

echo $dest ;
cp -r $src $dest ;
rm -R $src ;
ln -s $dest $src ;
echo 'done'

I also tried with '\\' (adding '\ ' to the var). also got me some errors.

Anyone knows what am I doing wrong? tnx

Upvotes: 0

Views: 166

Answers (3)

Gilles Quénot
Gilles Quénot

Reputation: 185126

Try this :

dest="$HOME/Videos-win/file name with spaces"
src="$HOME/Downloads/file name with spaces"

echo "$dest"
cp -r "$src" "$dest"
rm -R "$src"
ln -s "$dest" "$src"
echo 'done'

Please, USE MORE QUOTES! They are vital. Also, learn the difference between ' and " and `. See http://mywiki.wooledge.org/Quotes and http://wiki.bash-hackers.org/syntax/words

Upvotes: 2

John3136
John3136

Reputation: 29265

Your variables will have the "spaced" values, but then the spaces will be passed through to the the cp rm and ln commands.

Put double quotes around the variables where you actually use them to ensure the whole value (including spaces) is passed to the command as a single argument.

try:

cp -r "$src" "$dest"
rm -R "$src"
ln -s "$dest" "$src"

... and you don't need all the semicolons...

Upvotes: 1

Reimeus
Reimeus

Reputation: 159784

Try using double quotes:

cp -r "$src" "$dest" ;

...

Upvotes: 0

Related Questions