0

When I execute:

varx=$(echo "a  b"|sed -r -e "s/\s/\\\ /g"); echo $varx

The output will be:

a\ \ b

But when I execute the following script with the argument "a b" (folder a b exists):

#!/bin/bash
set -x
target=$(echo ${1} | sed -r -e "s/\s/_/g")
source=$(echo ${1} | sed -r -e "s/\s/\\\ /g")
mv ${source} ${target}
set +x

The output will be:

++ echo a b
++ sed -r -e 's/\s/_/g'
+ target=a_b
++ echo a b
++ sed -r -e 's/\s/\\ /g'
+ source='a\ b'                       1) question
+ mv 'a\' b a_b                       2) question
mv: target ‘a_b’ is not a directory
+ set +x

3 questions:

1) Why source='a\ b' and not 'a\ \ b' ?

2) Why mv 'a\' b a_b and not mv 'a\ b' a_b according to the previously calculated source value?

3) And how to force the script do the same that the command line version does?

ka3ak
  • 2,435
  • 2
  • 30
  • 57
  • Possible duplicate of [When to wrap quotes around a variable](http://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-variable) – tripleee May 26 '16 at 12:09

1 Answers1

1

Add double quotes to $1:

source=$(echo "${1}" | sed -r -e "s/\s/\\\ /g")
target=$(echo "${1}" | sed -r -e "s/\s/_/g")
echo mv \"${source}\" \"${target}\"

In your script, the echo command process a and b as parameters. With double quotes, $1 is not splitted.

To illustrate :

$ echo one     two
one two
$ echo "one     two"
one     two
SLePort
  • 15,211
  • 3
  • 34
  • 44
  • More generally, any variable which contains a file name should always be double-quoted. See further http://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-variable – tripleee May 26 '16 at 12:09
  • Thank you. The final solution was not to use "source" variable at all so that the script looked so: target=$(echo "${1}" | sed -r -e "s/\s/_/g") mv "${1}" "${target}" – ka3ak May 26 '16 at 13:16