J Freebird J Freebird - 1 year ago 42
Bash Question

Shell script: Whitespace in file names

I have a shell script that processes some files. The problem is that there might be white spaces in file names, I did:

FILE=`echo $FILE | sed -e 's/[[:space:]]/\\ /g'`
cat $FILE

So the variable
is a file name which is passed in from some other program. It may contain white spaces. I used
to escape white space with
in order to make the command line utilities be able to process it.

The problem is that it doesn't work.
echo $FILE | sed -e 's/[[:space:]]/\\ /g'
itself works as expected, but when assigned to
, the escape char
disappeared again. As a result,
will interpret it as more than 1 arguments. I wonder why it behaves like this? Is there anyway to avoid it? And what if there're multiple white spaces, say
some terrible file.txt
, which should be replaced by
some\ \ \ terrible\ \ file.txt
. Thanks.

Answer Source

Don’t make it more complicated than it is.

cat "$FILE"

That’s all you need. Note the quotes around the variable. They prevent the variable from being expanded and split at whitespace. You should always write your shell programs like that. Always put quotes around all your variables, unless you really want the shell to expand them.

for i in $pattern; do

That would be ok.