This is similar to Stéphane Chazelas' answer, but uses process substitution and a shell function instead of a heredoc to provide the user & password:
#!/bin/bash
printconf() {
cat <<-EOF
[mysql]
user=root
password=supersecretpassword
EOF
}
mysql --defaults-extra-file=<(printconf) -e 'CREATE DATABASE example'
The function (printconf
) just outputs a correctly formatted mysql conf file.
IMO, this is more readable than having multiple heredocs on the one line.
It still has the user & password details embedded in the script (so doesn't require an external file like ~/.my.cnf
) and still avoids exposing the password in the kernel's process table (i.e. via ps
, pgrep
, etc).
NOTE: This requires a modern shell that supports process substitution (e.g. bash
, zsh
, or ksh
).
The script contains a plain text password so should be adequately protected by ownership, group, permissions, and or ACLs. i.e. at the very least, it should not be world-readable.