assigning SED output to a variable = trouble!

i'm on a Mac running BSD unix.

i have a script in which i ask the user to input the name of a mounted volume. i then call SED to substitute backslashes and spaces in place of the spaces. that looks like this:

echo "Enter the name of the volume"
read Volume
echo "You've chosen \"$Volume\""
# remove spaces from name of Volume
echo $Volume | sed 's/ /\\ /g'

if i enter "old mac hd" for the volume name when prompted, it returns with:
"old/ mac/ hd" which is perfect!

but... if i then want to assign this output to a variable for later use, it doesn't work:

uVolume=`echo "$Volume" | sed 's/ /\\ /g'`
echo $uVolume

this returns:
"old mac hd" and NOT "old/ mac/ hd" as i'd like. and, as i'll be using the full directory path in a later portion of the script, i kinda need those backslashes!

i'm assuming that i'm missing simple syntax here. thoughts/comments/questions?

uVolume=`echo "$Volume" | sed 's/ /\\\ /g'`

If you are using bash, you can do it without any external commands:

uVolume=${Volume// /\\ }

Worked for me:

$ cat ll.sh
echo "Enter the name of the volume"
read Volume
echo "You've chosen \"$Volume\""
# remove spaces from name of Volume
echo $Volume | sed 's/ /\\ /g'


$ sh ll.sh
Enter the name of the volume
old mac hd
You've chosen "old mac hd"
old\ mac\ hd

FYI: Im running CentOs 5.2 (Red Hat)

That's exactly what hungryd said: It works when sent to the standard output.

His problem was with the extra level of parsing when assigned to a variable via command substitution.

My Bad, try this: (ah he already said it, duh... good thing the day is over)

echo "Enter the name of the volume"
read Volume
echo "You've chosen \"$Volume\""
# remove spaces from name of Volume
uVolume=`echo "$Volume" | sed 's/ /\\\ /g'`
echo $uVolume

Enter the name of the volume
old mac hd
You've chosen "old mac hd"
old\ mac\ hd

ikon,

that worked. can you or the others explain the syntax for me?

i'd used:
uVolume=`echo "$Volume" | sed 's/ /\\ /g'` and got no results

you suggested:
uVolume=`echo "$Volume" | sed 's/ /\\\ /g'` and i get exactly the results i wanted.

what does that extra "\" tell the code?

also my thanks to cfajohnson! didn't mention that before, gents, sorry.

There's another way to do the same:

$ echo $myvar
asd sdd aa
$ myvar1=`echo "$myvar" | sed 's/ /\\ /g'`
$ echo $myvar1
asd sdd aa
$ myvar1=$(echo "$myvar" | sed 's/ /\\ /g')
$ echo $myvar1
asd\ sdd\ aa

For an explanation see the section 'Command Substitution' in bash's man page (assuming you're using bash).