Bash – How to add a password to a BASH script

bashpasswordscripting

I want to create a script to run the following BASH command:

mysqldump -u [username] -p [db_name] > [path to backup file]

Which results in a backup file. When running this in BASH, it prompts for a password before continuing.

How do I craft this in a BASH script so that the password is automatically entered?

Can this be done securely?

Best Answer

The best kind of approach here is to do something like:

mysqldump --defaults-extra-file=/path/to/auth.cnf ...

Where auth.cnf looks like:

[client]
user=the-user
password=the-password

Then make sure the file is only readable by whomever is meant to run that script. The script itself can be world readable.

Related Question