Course contentsShow
← Linux
Lesson 170 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Secure Credential Injection

Pass sensitive keys into scripts without exposing them in logs.

In this lesson, you will learn how to provide sensitive passwords or API keys to your Bash scripts without leaving them visible in your shell history or system logs.

The Problem with Plain Text

When you write a script that requires a secret—like a database password—it is tempting to hardcode it as a variable. However, doing this is dangerous: anyone with access to your system can see the script, and if you export the variable, it might be captured in log files or displayed in ps command outputs.

Using Environment Variables and Files

Instead of hardcoding, we use Secure Credential Injection. This means providing the secret at runtime from a source that the script doesn't "own" and that isn't logged.

Method 1: Using Files with Restricted Permissions

The safest way to handle secrets is to store them in a file that only your user can read. By using chmod 600, you ensure no other user on the system can peek at your credentials.

Your script can then read the value using file redirection:

# Read the secret from a secure file into a variable
SECRET=$(cat /home/user/.db_password)

# Use the secret in your command
mysql -u admin -p"$SECRET"

Method 2: Injecting via Environment Variables

If you want to keep the password out of the script entirely, you can pass it as an environment variable right before the command. By prepending the variable to the command, the variable exists only in the memory space of that specific execution.

# Inject the password without storing it in a file
DB_PASS='super-secret-key' ./run_backup.sh

Inside run_backup.sh, you access it simply by using $DB_PASS. Because you provided it this way, the secret is not written to your shell history file (as long as you start the command with a space, depending on your shell config) and it never sits inside the script file itself.

Important Note on Security

While these methods prevent accidental exposure in your source code, remember that any process running as your user can still read the memory of your scripts. Always ensure your environment is restricted to the minimum set of users required to perform the task.

Key Takeaway: Never hardcode sensitive data in your scripts; instead, inject secrets at runtime using restricted files or transient environment variables to keep your credentials out of logs and history files.