Handling Secrets and Credentials in Scripts

Su Suriya Ravichandran Updated 06 Dec 2026
14 min read ·Lesson 158 of 205

A secret is any value that grants access: a password, an API token, a database connection string with a password in it, a private key, a cloud access key or a session cookie. Automation scripts need secrets all the time, to call APIs, log in to databases, push to registries or copy files to servers.

Handling a secret well means two things. First, the secret must reach the program that needs it. Second, it must reach only that program: not the script file, not the Git history, not the process list, not a log, not a trace, not the shell history and not a temporary file that other users can read. Each of these places is a real and common way that credentials leak.

This lesson shows where secrets leak from Bash scripts, demonstrates each leak, and then shows the techniques that keep a secret on its narrow path.

Understanding the Concept

A Bash script can obtain and pass a secret in several ways. They differ in who else can see it:

How the secret travelsWho can see it
Written in the scriptEveryone who can read the script or its repository history
Command-line argumentEvery user on the machine, through ps and /proc/PID/cmdline
Exported environment variableThe same user and root, through /proc/PID/environ; also every child process
Shell trace (set -x), logs, error messagesWhoever reads the terminal output or the log files
Temporary file with default permissionsOften every user on the machine
Standard input or a pipe from a built-inOnly the receiving process
A file with mode 600Only the owner (and root)

The safest paths are at the bottom of the table: a private file that the script reads, and standard input to pass the secret to the next program. The rest of this lesson explains why.

Leak 1: Secrets in the Script or Repository

A line such as API_TOKEN='s3cr3t-abc123' in a script is the most common leak of all. The script gets copied, shared, attached to tickets and committed to Git. Once a secret is committed, deleting the line does not remove it: it stays in every earlier commit and every clone.

Keep secrets out of the script and load them at run time from somewhere that is not shared: a private file, a secrets manager or a credential provided by the service manager. If a secret was ever committed, treat it as exposed and revoke and replace it; cleaning the history is not enough, because copies may already exist.

Leak 2: Command-Line Arguments

Every process's argument list is readable by every user on a normal Linux system. The following test starts a process with a token in its arguments, then looks at it as root and as the unprivileged user nobody:

token='s3cr3t-abc123'
bash -c 'sleep 2; : "$1"' _ "--token=$token" &
pid=$!
sleep 0.3
ps -o user=,args= -p "$pid"
setpriv --reuid=nobody --regid=nogroup --clear-groups ps -o args= -p "$pid"
root     bash -c sleep 2; : "$1" _ --token=s3cr3t-abc123
bash -c sleep 2; : "$1" _ --token=s3cr3t-abc123

The second line was produced by a different, unprivileged user, and it still shows the token. Any program that runs for even a moment with a secret in its arguments, for example curl -H "Authorization: Bearer $token" or mysql -p"$password", exposes it this way.

The exception is built-in commands. printf, echo and read run inside the current Bash process and do not start a new process, so their arguments never appear in a process list. That is why printf '%s' "$token" | program is safe, while /usr/bin/printf '%s' "$token" | program would not be.

Leak 3: Environment Variables

Environment variables are better than arguments, but they are not private either:

API_TOKEN=$token bash -c 'sleep 2' &
pid2=$!
sleep 0.3
tr '\0' '\n' < /proc/$pid2/environ | grep '^API_TOKEN'
setpriv --reuid=nobody --regid=nogroup --clear-groups cat /proc/$pid2/environ
ls -l /proc/$pid2/environ
API_TOKEN=s3cr3t-abc123
cat: /proc/588/environ: Permission denied
-r-------- 1 root root 0 Nov 24 09:01 /proc/588/environ

Other users cannot read a process's environment, but the same user and root can. The bigger problem is inheritance: an exported variable is copied into every child process, including programs that log their environment when they crash, debugging tools and third-party scripts:

export DB_PASS=hunter2
bash -c 'echo "child sees: ${DB_PASS-unset}"'
unset DB_PASS
SECRET=only-for-this bash -c 'echo "child sees: $SECRET"'
echo "parent: ${SECRET-unset}"
child sees: hunter2
child sees: only-for-this
parent: unset

When a program can only take a secret from the environment, use the NAME=value command form shown on the second line. It sets the variable for that one command, without exporting it to everything else the script runs. Never export a secret for the whole script.

Leak 4: Traces, Logs and Error Messages

set -x (lesson 126) prints every command after expansion, so it prints secrets too:

( set -x; curl_pw=$token; echo "using it" )
+ curl_pw=s3cr3t-abc123
+ echo 'using it'
using it

Traces are often switched on while debugging and then pasted into tickets or chat. In scripts that handle secrets, run set +x at the start, or wrap the lines that touch the secret in set +x ... set -x. The same care applies to logs and error messages: never print a secret, even partly, except as a short masked suffix such as ****c123 that helps identify which token was used.

Interactive shells have one more trap: commands typed at the prompt are saved to ~/.bash_history. Avoid typing secrets as part of a command. On systems where HISTCONTROL includes ignorespace (Ubuntu's default .bashrc sets ignoreboth), a command that starts with a space is not saved, but a hidden prompt is the better habit.

Leak 5: Files with Default Permissions

New files get their permissions from the umask (lesson 72). With the common umask 022, new files are readable by everyone. A script that writes a token, a downloaded credential or an API response containing personal data must create its files privately. umask 077 makes every file the script creates readable only by its owner:

umask 077; f=$(mktemp); stat -c '%a %n' "$f"
600 /tmp/tmp.W854siv6yr

The same check works the other way round: before reading a secret from a file, confirm that nobody else can read or change it. The permission bits for "group" and "others" are the last two octal digits, so the test is whether mode & 077 is zero:

printf 'x\n' > token.txt; chmod 644 token.txt
perm=$(stat -c '%a' token.txt); (( 8#$perm & 8#077 )) && echo "too open: $perm"
chmod 600 token.txt
perm=$(stat -c '%a' token.txt); (( 8#$perm & 8#077 )) || echo "ok: $perm"
too open: 644
ok: 600

8# tells Bash that the digits are octal. SSH applies the same rule to private keys and refuses keys that others can read.

Getting the Secret into the Script

Reading from a Private File

A file in the user's configuration folder, with mode 600, is simple and works everywhere. Read only the first line, exactly as it is:

IFS= read -r token < "$token_file"

read is a built-in, so the token never appears in a process list, and unlike token=$(cat "$token_file") no extra process is started.

Prompting Without Showing the Input

When a person runs the script, read -s reads without echoing the typed characters:

IFS= read -rs -p 'Password: ' pw; echo >&2

-s turns off echo only when standard input is a terminal. -p likewise shows its prompt only on a terminal. The echo >&2 moves to a new line after the hidden input. Check [[ -t 0 ]] before prompting, so the script fails clearly instead of waiting when it runs without a terminal, for example from cron.

Credentials from the Service Manager

When a script runs as a systemd service, the unit can provide credentials with LoadCredential=name:/path or SetCredentialEncrypted=. systemd places them in a private folder whose path is in the environment variable CREDENTIALS_DIRECTORY, readable only by the service. The script then reads $CREDENTIALS_DIRECTORY/name. Secret managers such as HashiCorp Vault, cloud secret services, pass or the CI system's secret store work in a similar way: the script asks for the secret at run time and never stores it.

Passing the Secret On

The last step is handing the secret to the program that uses it, without putting it in that program's arguments. Many tools have a way to read secrets from standard input or from a file:

ToolSafe way
curl-H @- (headers from stdin), -K - (config from stdin), --netrc-file FILE
docker login--password-stdin
mysql, psqloption files (--defaults-extra-file), ~/.pgpass, or the MYSQL_PWD/PGPASSWORD environment variable for that command only
ssh, gitkeys and credential helpers instead of passwords
gpg, openssl--passphrase-fd 0, -pass stdin or -pass file:

The following test uses a small local test server that answers HTTP 200 only when it receives the header Authorization: Bearer s3cr3t-abc123, and 401 otherwise:

url=http://127.0.0.1:8765/items
printf 'header = "Authorization: Bearer %s"\n' "$token" | curl -s --noproxy '*' -K - "$url"
printf 'Authorization: Bearer %s\n' "$token" | curl -s --noproxy '*' -H @- "$url"
printf 'Authorization: Bearer %s\n' wrong | curl -s --noproxy '*' -o /dev/null -w '%{http_code}\n' -H @- "$url"

(--noproxy '*' only stops curl from sending these local test requests through a proxy server.)

{"path": "/items", "authorized": true}
{"path": "/items", "authorized": true}
401

In both successful forms, the token travelled from the built-in printf through a pipe into curl. It was never part of any argument list.

When the secret is no longer needed, unset token removes it from the script's memory, so a later function or a debugging session cannot print it by accident.

A Complete Example: Calling an API Without Exposing the Token

api-get.sh fetches one path from an API. It looks for the token in a systemd credentials folder, then in a private file, and finally asks for it at a hidden prompt. It refuses token files that other users could read or change, never traces itself, never puts the token in an argument list or the environment, and shows only the last four characters in its log line.

#!/usr/bin/env bash
# api-get.sh: call an API endpoint without exposing the token
# usage: api-get.sh PATH
# The token is read, in this order, from:
#   1. $CREDENTIALS_DIRECTORY/api_token   (systemd LoadCredential=)
#   2. the file named in $API_TOKEN_FILE   (default ~/.config/api-get/token)
#   3. a hidden prompt, when standard input is a terminal
set -uo pipefail
umask 077                                   # any file we create is private
set +x                                      # never trace this script

base_url=${API_URL:-http://127.0.0.1:8765}
token_file=${API_TOKEN_FILE:-$HOME/.config/api-get/token}

die() { printf '%s: %s\n' "${0##*/}" "$1" >&2; exit "${2:-1}"; }

# Refuse files that other users can read or change, or that we do not own
check_private_file() {
  local file=$1 perm owner
  [[ -f $file && ! -L $file ]] || die "not a regular file: ${file@Q}"
  read -r perm owner < <(stat -c '%a %u' -- "$file") || die "cannot check ${file@Q}"
  (( owner == EUID )) || die "${file@Q} is owned by user $owner, not by you"
  (( (8#$perm & 8#077) == 0 )) || die "${file@Q} has mode $perm; run: chmod 600 ${file@Q}"
}

load_token() {
  local file
  if [[ -n ${CREDENTIALS_DIRECTORY-} && -f $CREDENTIALS_DIRECTORY/api_token ]]; then
    file=$CREDENTIALS_DIRECTORY/api_token
  elif [[ -e $token_file ]]; then
    file=$token_file
    check_private_file "$file"
  elif [[ -t 0 ]]; then
    IFS= read -rs -p 'API token: ' token; echo >&2
    [[ -n $token ]] || die 'no token entered'
    return
  else
    die "no token: create ${token_file@Q} (mode 600) or run in a terminal"
  fi
  IFS= read -r token < "$file" || [[ -n ${token-} ]] || die "token file is empty: ${file@Q}"
}

mask() { local s=$1; printf '****%s' "${s: -4}"; }

(( $# == 1 )) || die 'usage: api-get.sh PATH' 2
path=$1
[[ $path =~ ^/[A-Za-z0-9/_.-]*$ ]] || die "invalid path: ${path@Q}" 2

token=
load_token
[[ $token =~ ^[A-Za-z0-9._-]{8,200}$ ]] || die 'token has an unexpected format'

printf 'GET %s (token %s)\n' "$path" "$(mask "$token")" >&2

# The header goes to curl on standard input: printf is a built-in, so the
# token never appears in any process's argument list or environment.
status=$(printf 'Authorization: Bearer %s\n' "$token" |
  curl -sS --noproxy '*' -H @- -o response.json -w '%{http_code}' -- "$base_url$path") ||
  die 'request failed'
unset token

if [[ $status == 200 ]]; then
  cat response.json
else
  die "server answered HTTP $status"
fi

How It Works

  • Safe defaults first. umask 077 makes response.json (which may contain private data) readable only by the owner. set +x switches tracing off even when someone runs bash -x api-get.sh.
  • Three token sources. The systemd credentials folder is checked first, because it is the most controlled source. A token file is used next, but only after check_private_file confirms that it is a regular file (not a symbolic link that could point elsewhere), that the current user owns it, and that its mode gives no access to group or others. The hidden prompt is used only when standard input is a terminal; otherwise the script stops with an instruction.
  • Reading the file. IFS= read -r token < "$file" reads the first line exactly. The || [[ -n ${token-} ]] part accepts a file whose only line has no final newline, which is common when a token is pasted into an editor or written with printf '%s'.
  • Validation. The path must start with / and contain only safe URL characters, so it cannot add options or shell syntax. The token must look like a token: a missing line or a pasted line with spaces is reported before anything is sent.
  • Masking. ${s: -4} takes the last four characters (the space before -4 is required, otherwise Bash reads :- as a default value). The log line identifies which token was used without revealing it.
  • Passing the token. The header is written by the built-in printf into a pipe, and curl -H @- reads it from standard input. --noproxy '*' keeps this local test from going through a proxy; drop it for a real API. -w '%{http_code}' prints only the HTTP status, which the command substitution captures. -- ends curl's options before the URL.
  • Clean-up. unset token removes the secret as soon as it is no longer needed.

Running the Complete Example

The test server from the previous section is running. The token file is set with API_TOKEN_FILE=token.txt, which does not exist yet, and standard input is not a terminal:

export API_TOKEN_FILE=token.txt
./api-get.sh /items < /dev/null; echo "status $?"
printf 's3cr3t-abc123\n' > token.txt; chmod 644 token.txt
./api-get.sh /items < /dev/null; echo "status $?"
chmod 600 token.txt
./api-get.sh /items < /dev/null; echo "status $?"; stat -c '%a %n' response.json
api-get.sh: no token: create 'token.txt' (mode 600) or run in a terminal
status 1
api-get.sh: 'token.txt' has mode 644; run: chmod 600 'token.txt'
status 1
GET /items (token ****c123)
{"path": "/items", "authorized": true}
status 0
600 response.json

The script refused to wait for a prompt that nobody could answer, refused a token file readable by everyone and told the user how to fix it, then succeeded once the file was private. The response file was created with mode 600 because of the umask.

Other sources and problems are handled as well:

printf 'wrong-token-1\n' > other.token; chmod 600 other.token
API_TOKEN_FILE=other.token ./api-get.sh /items < /dev/null; echo "status $?"
mkdir -p creds; printf 's3cr3t-abc123' > creds/api_token
CREDENTIALS_DIRECTORY=$PWD/creds ./api-get.sh /orders/7 < /dev/null; echo "status $?"
./api-get.sh '/items; rm -rf /' < /dev/null; echo "status $?"
ln -sf other.token link.token
API_TOKEN_FILE=link.token ./api-get.sh /items < /dev/null; echo "status $?"
cp other.token nobody.token; chown nobody nobody.token
API_TOKEN_FILE=nobody.token ./api-get.sh /items < /dev/null; echo "status $?"
GET /items (token ****en-1)
api-get.sh: server answered HTTP 401
status 1
GET /orders/7 (token ****c123)
{"path": "/orders/7", "authorized": true}
status 0
api-get.sh: invalid path: '/items; rm -rf /'
status 2
api-get.sh: not a regular file: 'link.token'
status 1
api-get.sh: 'nobody.token' is owned by user 65534, not by you
status 1

The wrong token was sent and rejected by the server, and the masked suffix shows which token it was. The systemd-style credentials folder worked with a token file that has no final newline. The path with shell syntax, the symbolic link and the file owned by another user were all refused before any request was made. Finally, running the whole script under bash -x and searching the trace for the token finds nothing, because set +x switched tracing off before the token was loaded:

bash -x ./api-get.sh /items < /dev/null 2>&1 | grep -c s3cr3t
0

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Handling Secrets and Credentials in Scripts and get answers drawn from it.

Signed-in readers only.