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?

2
  • 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
    Commented Oct 17, 2021 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? 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
    Commented Oct 18, 2021 at 3:45

1 Answer 1

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.

1
  • 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
    Commented Oct 17, 2021 at 21:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .