Skip to content
Advertisement

Extra backslash when storing grep in a value

In a bash script I have:

Check="grep -e '"'(-S mount)'"' /etc/audit/audit.rules"
set -x

When you run it it shows it as:

CHECK='grep -e '''(-S mount)''' /etc/audit/audit.rules'

Now it works exactly what I want but I want to understand it. Why is there 2 extra ‘s?

Advertisement

Answer

The output from set -x uses single quotes. So the outer double quotes were replaced with single quotes but you can’t escape single quotes inside a single quoted string so when it then replaced the inner double quotes it needed, instead, to replace them with ''' which ends the single quoted string, then has an escaped single quote, and then starts the next single quoted string.

Also, as an aside, don’t store commands in strings. It will only cause you pain later. See Bash FAQ 050 for more about this.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement