1

I'm trying to write a systemd service file without resorting to using an external script.

I need to query an SQLite database and write the contents to a file. But my query uses double quotes. I need to wrap the query in single quotes and since systemd doesn't use a shell, I need to manually use one. So how do I accomplish this?

ExecStart=sh -c 'sqlite3 dbfile.db 'SELECT "The db value is: "||value FROM table' > output.log'

I have tried escaping the inner single quotes, but for some reason that doesn't work.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Put your command in a separate script, and set its name to ExecStart value – pierpy Apr 18 '21 at 04:28
  • i am not sure, but does `echo 'cmd str1' "cmd str2"...etc | sh ` work? you can join multiple strings wrapped in varied quotes. or even otherwise, regular escaping with `\ ` should work, right? – kevinnls Apr 18 '21 at 05:06
  • Related: *[How to escape single quotes within single quoted strings](https://stackoverflow.com/questions/1250079/)* – Peter Mortensen Aug 16 '23 at 19:27
  • Though there is probably a specific canonical question for this somewhere. This question *must* be a duplicate. – Peter Mortensen Aug 16 '23 at 19:27
  • Possible lead: *[How can I keep quotes in Bash arguments?](https://stackoverflow.com/questions/1668649/how-to-keep-quotes-in-bash-arguments)* – Peter Mortensen Aug 16 '23 at 19:37

1 Answers1

1

Try this:

ExecStart=sh -c 'sqlite3 dbfile.db '\''SELECT "The db value is: "||value FROM table'\'' > output.log'

I used to use MySQL and double quotes work as well. You can also give it a shot:

ExecStart=sh -c 'sqlite3 dbfile.db "SELECT \"The db value is: \"||value FROM table" > output.log'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Taylor G.
  • 661
  • 3
  • 10
  • Can you explain what `'\''` means? I understand the escaping, but it's doubled? –  Apr 19 '21 at 00:36
  • The first `'` actually closed the command, let `\'` escape single quote out of the whole quotes, and the last `'` concats the rest of command. A clearer example: `'This is '\'' escaped single quote'` consists of `'This is '` + `\'` + `' escaped single quote'`. – Taylor G. Apr 19 '21 at 02:46