There's something wrong with this command or I'm not seeing my mistake. I also needed to exclude disabled users and users with UID over 500. This is the SQL command I need to use

INSERT INTO `mailbox` (`username`, `password`, `name`, `maildir`, `quota`, `local_part`, `domain`, `created`, `modified`, `active`) VALUES ('$username, '$pass', '', '$xxxx', 0, 'xxx', 'xxx', 'date --rfc-3339=date', 'date --rfc-3339=date', 1);"

This is the script I wrote. This is the output errors.

  • 2
    Please, don't post images of text. – Kusalananda Dec 16 '18 at 12:59
  • 2
    Please take some time to write a quality question, and in particular a meaningful title. e.g. I advise avoiding simple titles "as please help me". I could also swear this is a repost. – Rui F Ribeiro Dec 16 '18 at 14:04

The issue is that the backticks in the SQL are treated as command substitutions by the shell. The shell would try to run backticked string as a command to replace that bit with the output of that particular command.

The shell does this because you echo the string with double quotes.

To solve this particular issue, escape each backtick as \`.

Ideally, you would pass the SQL as a single quoted string, but that would mean that the variables wouldn't be expanded.

You can also do it this way, which would be safer:

printf 'INSERT INTO `mailbox` (`username`, `password`, `name`, `maildir`, `quota`, `local_part`, `domain`, `created`, `modified`, `active`) VALUES ("%s", "%s", "", "%s", 0, "xxx", "xxx", "date --rfc-3339=date", "date --rfc-3339=date", 1);\n' "$username" "$pass" "$xxxx"

... assuming the particular database you are using can handle double quoted field data.

  • Kusalananda it did take the usernames and passwords and exclude the disabled users, but for each user it printed the whole INSERT INTO mailbox ... phrase as it is with only the usernames and passwords being filled out. What I forgot in the original question was to mention that I had written previously echo "INSERT INTO ..." >> test.sql – John Doe Dec 16 '18 at 13:16
  • @JohnDoe Well, you can redirect the output of printf too... – Kusalananda Dec 16 '18 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.