1

I have the following code in my script:

mapfile results < <(mysql --batch -u $DB_USERNAME -p$DB_PASSWORD $DB_DATABASE < query.sql)

and it works fine if running from command line. But if running from /var/spool/cron/root then $results variable contains nothing.

Why and how to fix?

Dims
  • 3,181
  • 9
  • 49
  • 107
  • 1
    Paths and environment all change when you run in cron. Use an absolute path for query.sql and any other file you might need. – LSerni Oct 17 '21 at 20:13
  • Aside from env issues, you should quote your variables. Unquoted variables are a disaster waiting to happen - see [Why does my shell script choke on whitespace or other special characters?](https://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters) Also you should probably use a mysql option file (e.g. `~/.my.cnf`, readable only by you) rather than put the password on the command line....any process running on the system can scan the process table (e.g. run `ps` or trawl through `/proc/*/cmdline`) and extract the password. – cas Oct 18 '21 at 03:45

1 Answers1

1

Since the command part of a crontab line is interpreted with /bin/sh, which supports a simpler syntax, you'll have to wrap your command in a bash script, and invoke that script from command part.

Also, your environment variables (DB_*, PATH) and mysql setup MUST be manually propagated to your cron environment with care.

waltinator
  • 4,439
  • 1
  • 16
  • 21
  • Also, you may not want to store the password in an environment variable since usually all processes by all users running on the machine can see it. – Ned64 Oct 17 '21 at 21:21