-1

I want to escape back quotes in a variable before writing it to a file. Unfortunately some of these lines have some disagreeable items.

(I want to avoid foo from expanding. I want foo="ModPagespeedLoadFromFileRuleMatch disallow .*" to be taken literally and substitution run on it. I do not want any expansion. It is just a directive to be placed in a file. )

foo="ModPagespeedLoadFromFileRuleMatch disallow .*"
echo ${foo//\\/\\\\}

This gives me:

ModPagespeedLoadFromFileRuleMatch disallow . .. .bash_history .bashrc .cloud-locale-test.skip .filemin .gnupg .local .mysql_history .profile .rnd .rpmdb .ssh

I also tried like this:

foo='ModPagespeedLoadFromFileRuleMatch disallow .*';
bar=$( printf "$foo" | sed 's/\\/\\\\/g' );
echo $bar

foo='ModPagespeedLoadFromFileRuleMatch disallow .*';
bar=$( echo "$foo" | sed 's/\\/\\\\/g' );
echo $bar

Same problem.

What am I missing here?

PS. Try this:

foo='ModPagespeedLoadFromFileRuleMatch disallow .*' 
echo "$foo" 

Then try this (I do not want this to happen when piping):

foo='ModPagespeedLoadFromFileRuleMatch disallow .*' 
echo "$foo" | 

Note the pipe in the second example

ANSWER:

foo="ModPagespeedLoadFromFileRuleMatch\ disallow .*"
echo "${foo//\\/\\\\}"

foo='ModPagespeedLoadFromFileRuleMatch disallow .*';
bar=$( printf "$foo" | sed 's/\\/\\\\/g' )
echo "$bar"

foo='ModPagespeedLoadFromFileRuleMatch disallow .*';
bar=$( echo "$foo" | sed 's/\\/\\\\/g' );
echo "$bar"
Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
conanDrum
  • 457

1 Answers1

5

The issue is that you're not quoting the expansion that you pass to echo.

Not quoting the expansion invokes field splitting of the resulting string into words on whitespaces (assuming the default value of $IFS), and, crucially, file name generation (globbing) on each of the words.

One of the words is .*, and this would expand to all hidden names in the current directory.

Instead:

foo="ModPagespeedLoadFromFileRuleMatch disallow .*"
echo "${foo//\\/\\\\}"

Or even better,

foo="ModPagespeedLoadFromFileRuleMatch disallow .*"
printf '%s\n' "${foo//\\/\\\\}"

This would output

ModPagespeedLoadFromFileRuleMatch disallow .*

You have the same issue with echo $bar.

See also:

Kusalananda
  • 333,661