How to add a password to a BASH script

9,628

Solution 1

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.

Solution 2

Leaving a plain text password in any file is always a bad idea in case your system is ever compromised. Sometimes it is unavoidable. To make this "secure" you should limit this activity to a very limited user and also leave these sensitive options in a defaults file.

To solve your issue specifically, from the mysql man page:

If you use the short option form (-p), you cannot have a space 
between the option and the password. If you omit the password 
value following the --password or -p option on the command line, 
mysql prompts for one.

in order to fix this you would need to run:

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

or

mysqldump -u [username] -password=[password] [db_name] > [path to backup file]
Share:
9,628

Related videos on Youtube

Roy Hinkley
Author by

Roy Hinkley

Updated on September 18, 2022

Comments

  • Roy Hinkley
    Roy Hinkley over 1 year

    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?

  • Alaa Ali
    Alaa Ali almost 9 years
    And the command history (assuming no/default HISTIGNORE) and audit.log (if configured to log executed commands).
  • Stéphane Chazelas
    Stéphane Chazelas almost 9 years
    @AlaaAli, yes, though if in the case of a script, that won't go in a shell history file.
  • tangrs
    tangrs almost 9 years
    The original question also asked on how to do it securely. If you pass it on the command line, the password will show up in ps output as mentioned in some of the other comments.
  • dr_
    dr_ almost 9 years
    This is a correct answer but a bad idea.