lstipakov
lstipakov

Reputation: 3238

Bash quotes fun

I have code:

sudo_cmd="echo -e \\"$cmd\\" >> $CACHE_CONF"
echo "$sudo_cmd"

that prints string:

echo -e "K1 = 'memcached://host/'\nK2 = 'memcached://host/'\n" >> /opt/settings.py

that works fine if I execute it in shell, here is result in settings.py:

K1 = 'memcached://host/'
K2 = 'memcached://host/'

However, when I execute this command via ssh:

ssh $user@$host "sudo sh -c \"$sudo_cmd\"

result in settings.py is different:

K1 = memcached://host/nK2 = memcached://host/n

Despite -e option for echo, newline does not work.

What I am doing wrong?

Update:

str="a\nb"
cat >> settings.py <<< "$str"

also does not work.

Upvotes: 1

Views: 329

Answers (3)

sorpigal
sorpigal

Reputation: 26106

Your problem is with your escapes.

Presuming that

cmd="K1 = 'memcached://host/'\\nK2 = 'memcached://host/'\\n"

Then your sudo_cmd assignment needs to be

sudo_cmd="echo -e \\\"$cmd\\\" >> $CACHE_CONF"

Note the additional backslash escaping the quotes.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799330

The \ in \n is being processed by the shell that ssh is running in. Either use a heredoc/herestring with cat, or make the quoting more complex.

cmd=$'...\n...'
ssh ... "cat >> $CACHE_CONF" <<< "$cmd"

Upvotes: 0

Greg Reynolds
Greg Reynolds

Reputation: 10216

You need to escape your \n again in the $cmd string, so it would be \n, then that would transfer through to the new string properly.

Upvotes: 0

Related Questions