Issue
From another script used as a wrapper I'm trying to configure an AWS SNS alert that will be triggered by the webhook. The issue is that I'm loosing al the specal characters from SED command that will help me eliminate ASCI color characters from some custom commands like 'alerts':
printf 'aws sns publish --subject "$(hostname -f)" --message "$(alerts -v|sed 's/\x1b\[[0-9;]*m//g' && echo -e "\n\n" && alerts --components|sed 's/\x1b\[[0-9;]*m//g')"' > /opt/webhook/sns.sh
Basically I'm trying to redirect this command inside /opt/webhook/sns.sh to be executed.
Solution
printf
itself is interpreting the \x1b
, rather than writing it literally. I would move both command substitutions outside the format string, both for readability and to protect \x1b
from being interpreted by printf
.
printf 'aws sns publish --subject "%s" --message "%s"\n' \
'$(hostname -f)' \
"\$(alerts -v | sed 's/\x1b\[[0-9;]*m//g' &&
printf '\n\n' &&
alerts --components | sed 's/\x1b\[[0-9;]*m//g')" \
> /opt/webhook/sns.sh
You'll note the quoting is tricky; single quotes cannot appear inside a single-quoted string, so I use double quotes and explicitly escape the $
that starts the command substitution.
I would actually not use printf
at all, but cat
with a here document:
cat <<'EOF' > /opt/webhook/sns.sh
aws sns publish --subject "$(hostname -f)" --message "$(alerts -v|sed 's/\x1b\[[0-9;]*m//g' && echo -e "\n\n" && alerts --components|sed 's/\x1b\[[0-9;]*m//g')"
EOF
Ideally, alerts
would either provide a way to disable colored output or be smart enough to disable color output automatically when its standard output isn't a terminal, so you could dispense with the sed
command altogether.
Answered By - chepner