N
N
Nikolay Baranenko2020-07-30 16:49:25
linux
Nikolay Baranenko, 2020-07-30 16:49:25

How to properly escape $ and ' characters when passing them to ansible shell?

Hello.

I want to send the

docker ps -aq command via ansible shell | awk '{print $1}'

problem occurs with single quotes

tried tons of options:

ansible -m shell -a 'docker stop \$(docker ps -aq | awk \'{print \$1}\')' server01 -i ./ hosts

only worked like this

ansible -m shell -a "docker stop \$(docker ps -aq | awk \"{print \$1}\")" server01 -i ./hosts

BUT still interested in options with single.

ps I understand that in a specific case, docker ps -aq is enough)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Saboteur, 2020-07-31
@saboteur_kiev

Read the shell documentation for quotes.
In short:
1. Within single quotes, ALL characters lose their special meaning. Including backslash, so
'STRING1\'STRING2'
it's not an escaped single quote within quotes, but a single quoted string STRING1\ then unquoted STRING2 and then another opening single quote that is unclosed.
You can do this:
'STRING1'\''STRING2'
2. Inside double quotes, all characters lose their special meaning except $, backslash and backsingle quotes. Examples:
"${VARIABLE} \${VARIABLE} $(hostname) `hostname`"
VARIABLE value, string ${VARIABLE} which will be expanded later, result of hostname command called twice in different ways

M
MaxKozlov, 2020-07-30
@MaxKozlov

Single quotes are doubled if the outside is also single

X
xotkot, 2020-07-31
@xotkot

If you don't want to manually bother with escaping, you can do this:

cat <<'EOF' | jq -Rr '@sh'
dokcer stop $(docker ps -aq | awk '{print $1}')
EOF

we get:
'dokcer stop $(docker ps -aq | awk '\''{print $1}'\'')'

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question