I was trying to write a shell script to copy files. Here is what I have done.
workingDirectory=$(pwd | sed "s/ /\\ /g")
Now echo $workingDirectory
shows /home/user/Documents/Learning and Development/
.
But I know, in order for cp
command to work I need to replace spaces with \
(backslash+space). So I changed the sed
command slightly as,
workingDirectory=$(pwd | sed "s/ /\\\ /g")
So that, echo $workingDirectory
shows /home/user/Documents/Learning\ and\ Development/
. All good.
But when try to use cp
command as,
cp $workingDirectory/jad/jad /usr/bin/
I get errors,
cp: cannot stat ‘/home/user/Documents/Learning\\’: No such file or directory
cp: cannot stat ‘and\\’: No such file or directory
cp: cannot stat ‘Development/jad/jad’: No such file or directory
What could be the reason? How to resolve this?
EDIT
If I use the first sed
command, then the errors are
cp: cannot stat ‘/home/user/Documents/Learning’: No such file or directory
cp: cannot stat ‘and’: No such file or directory
cp: cannot stat ‘Development/jad/jad’: No such file or directory
Escaping a field separator inside a variable to prevent word splitting isn't useful: the shell will still split words on the separators listed in
$IFS
:So an obvious workaround for that would be setting
$IFS
to an empty string (and avoiding escaping spaces at all), essentially disabling word splitting entirely:However disabling word splitting entirely in general doesn't make too much sense. Unless you have good reasons to disable word splitting entirely for more than one command I suggest you simply use double quotes to prevent it limitedly to the strings that can possibly contain field separators: