Secure handling of sensitive information, such as passwords, is a crucial aspect of shell scripting. Especially in scenarios where shell scripts interact with databases or other services requiring authentication, it’s important to ensure that passwords are not exposed. In this article, we’ll cover some methods you can use to hide passwords in shell scripts.
Method 1: Using Environment Variables
Environment variables are a secure way to store sensitive information such as passwords, making them inaccessible to external users. Here’s how you can use an environment variable to store your password:
Set an environment variable in your current shell or in your .bashrc
or .bash_profile
file:
export DB_PASSWORD="your_password"
In your script, you can now reference this environment variable:
#!/bin/bash
USER="your_username"
DATABASE="your_database"
HOST="localhost"
PASSWORD=$DB_PASSWORD
QUERY='SELECT * FROM freshers_tbl'
mysql -u $USER -p$PASSWORD -D$DATABASE -h$HOST -e "$QUERY"
Method 2: Using a Protected File
Store your password in a separate file with restricted permissions:
Create a new file and write your password into it:
echo "your_password" > ~/.mypassword
Restrict the file permissions so that only the file owner can read it:
chmod 600 ~/.mypassword
Read the password from the file in your shell script:
#!/bin/bash
USER="your_username"
DATABASE="your_database"
HOST="localhost"
PASSWORD=$(cat ~/.mypassword)
QUERY='SELECT * FROM freshers_tbl'
mysql -u $USER -p$PASSWORD -D$DATABASE -h$HOST -e "$QUERY"
Method 3: Using MySQL Option Files (Specifically for MySQL)
In your home directory, create a file called .my.cnf
:
touch ~/.my.cnf
Edit the file and add the following content:
[client]
user=your_username
password=your_password
host=localhost
database=your_database
Restrict permissions on the file to ensure only the owner can read it:
chmod 600 ~/.my.cnf
Now, your MySQL command in the shell script becomes:
#!/bin/bash
QUERY='SELECT * FROM freshers_tbl'
mysql --defaults-file=~/.my.cnf -e "$QUERY"
More similar articles : Shell