5

I have the following files:

~/tmp/testbash$ l
file 1.test  move.sh*

where move.sh is:

#!/bin/bash
#-x

FILENAME='file\ .test'
echo $FILENAME
echo joo
mv $FILENAME test.test

When I run ./move.sh, I get this output and error:

file\ .test
joo
mv: target `test.test' is not a directory

The problem is that it executes the command as:

mv file .test test.test

and not as:

mv file\ .test test.test

How can I fix this?

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
1408786user
  • 1,868
  • 1
  • 21
  • 39
  • Please don't edit solutions into questions. Keeping answers separate lets them be voted on, commented on, and edited independently. Instead, click the checkbox by an answer you accept. – Charles Duffy May 08 '16 at 18:18
  • (...speaking to content: It's important to differentiate between data and syntax; a backslash in `foo\ bar` is syntax [which causes the following space to be treated as literal], whereas a backslash in `'foo\ bar'` is data). – Charles Duffy May 08 '16 at 18:20

2 Answers2

9

If the variable contains embedded spaces, then bracket the variable in double quotes (").

FILENAME='file .test'
mv "$FILENAME" test.test
octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
4

Use double quotes if you have spaces inside a variable value:

FILENAME='file\ .test'
echo "$FILENAME"
echo joo
mv "$FILENAME" test.test
Hari Menon
  • 33,649
  • 14
  • 85
  • 108
  • This would work if the name contained a **literal** backslash, not if the intent is to escape the space. See the answer the OP edited into their question (in the history, if no longer present when reading this comment), which didn't have that literal backslash present. – Charles Duffy May 08 '16 at 18:19