swiftapplications

Apple security for developers

Use the macOS security command to keep secrets out of scripts

Store, update, read and delete Keychain secrets from the terminal with the macOS security command, and pass a key to one command instead of your whole shell.

Updated 8 October 2026 3 min read

The short answer

The built-in security command reads and writes the login keychain: add-generic-password to store (-U to update), find-generic-password -w to read, delete-generic-password to remove. In scripts, read the key straight into the one command that needs it instead of exporting it.

The four commands you need

Store (prompts), update, read, delete
security add-generic-password -a "$USER" -s "anthropic-api-key" -w
security add-generic-password -U -a "$USER" -s "anthropic-api-key" -w
security find-generic-password -a "$USER" -s "anthropic-api-key" -w
security delete-generic-password -a "$USER" -s "anthropic-api-key"

-s is the service (what the secret is for), -a the account. Ending add-generic-password with -w and no value makes it prompt, so the secret stays out of your shell history.

In a script

deploy.sh
#!/bin/zsh
set -euo pipefail

# read at the last moment, give it to one process only
CLOUDFLARE_API_TOKEN="$(security find-generic-password -s cloudflare-token -w)" \
  npx wrangler deploy

Don’t echo the value, don’t export it, and don’t write it to a temp file.

The “security wants to use your keychain” prompt

macOS asks the first time a program reads an item created by another app. Click Allow for one-off reads; Always Allow trusts that program for good. When adding an item you can name trusted programs with -T, but trusting a general tool like /usr/bin/security means any script can read it silently.

The safe way to do this

MoltenRock

The encrypted vault for your API keys and AI agents

Your keys sealed by your Mac’s Secure Enclave, handed only to the local agents you approve, never written to a .env file. Free for Mac.

Get MoltenRock, free

Questions developers ask

How do I list my keychain items from the terminal?

security dump-keychain prints item attributes. Avoid its -d flag, which prints the secrets too.

Does security work over SSH?

Only if the login keychain is unlocked in that session; otherwise reads fail or prompt for the keychain password.

Is the security command safe for CI?

On a Mac CI runner, use a dedicated keychain created for the job and deleted afterwards, not the login keychain.