Keep It Simple Stupid

Shell: Quotes in a string

| comments

Shells (such as bash and zsh) have a long history and legacy, thus some things may seem illogical or just strange. For instance, using strings and variable substitutions in them; I’m not going to describe that in details here, you may refer to the Advanced Bash-Scripting Guide. I do want to share a trick of how to insert quotes in two other levels of quotes.

If your outermost quotes are " (a quotation mark), you insert the symbol like this:

$ echo "Here is the string: "'"'"AA BB"'"'
# prints => Here is the string: "AA BB"

Likewise, if the outermost quotes are ' (an apostrophe), insert it like this:

$ echo 'Here is the string: '"'"'AA BB'"'"
# prints => Here is the string: 'AA BB'

It’s very simple indeed! If you parse the string, here’s the results: ' (start the string) Here is the string: ' (end that string) "'" (insert an apostrophe quoted by quotation marks) ' (start another string) AA BB ' (end another string) "'" (quoted apostrophe).

You may argue that I could use the different quotes in these examples (like echo "Here is the string: 'AA BB'"), and that’s definitely true. Take a look at the script in my previous post, here’s a simplified excerpt:

su - -- -c "sqlite3 app.db 'delete from X where Y like "'"'"com%"'"'"'";

Here, the sqlite3 call with its arguments is quoted with " to be passed to su. The second parameter is a SQL query, quoted with ' (different from the outer quoting). And inside the query I need to insert a quoted string again, which is where I use the suggested trick. Can you parse that?