There is no escaped space in the variable to keep. When you enter ~/A Directory/
at the prompt, the variable directory
contains ~/A Directory/
. If you're having trouble with this space later in your script, it's because you forgot the double quotes around variable expansions.
read -e -p "Enter a Directory: " directory
ls -- "$directory"
cd -- "$directory"
The --
is in case the value starts with -
, so that it isn't treated as an option.
If for some reason you want to add a backslash before spaces, you can do it with bash's string manipulation features.
echo "${directory// /\\ }"
This is highly unlikely to be useful though. If you need to print out the directory in a form that will be parsed again, there will definitely be other characters to quote. Which characters depends on what's going to parse it, but at the very least tabs (and newlines, but your script is unable to read them) will need quoting if spaces do, and a backslash will also need to be quoted. Bash doesn't have a convenient way to do that. You can use sed, but be careful when passing the data to it — echo
does not print all arguments unmodified. An added difficulty command substitution strips trailing newlines, but you won't have newlines here.
quoted_directory=$(printf %s "$directory" | sed 's/[\\ '$'\t'']/\\&/')
Note also that nothing here expands the tilde at the beginning. (The output you show is faked, naughty you!) Tilde expansion only happens as part of source code parsing, it does not happen when the value of a variable is expanded. If you want to replace an initial tilde with the home directory, you'll need to do it manually.
read -e -p "Enter a Directory: " directory
if [[ $directory = \~/* ]]; then
directory="$HOME/${directory#*/}"
fi
ls -- "$directory"
cd -- "$directory"
cd
the echo output? – snoop Oct 03 '15 at 16:40