Storing Sensitive Values in .zshrc with macOS Keychain
Storing tokens and passwords directly in ~/.zshrc means they sit on disk in plaintext. macOS Keychain provides a built-in, encrypted alternative. Here’s how to use it.
Store a Secret
Section titled “Store a Secret”Use the security CLI to add a value to your Keychain:
security add-generic-password -a "$USER" -s 'my_secret_name' -w 'SECRET_VALUE'-a "$USER"— associates the entry with your macOS user account.-s 'my_secret_name'— a label to identify the secret (e.g.,GITHUB_TOKEN).-w 'SECRET_VALUE'— the actual secret value.
Retrieve a Secret
Section titled “Retrieve a Secret”To retrieve the value later:
security find-generic-password -a "$USER" -s 'my_secret_name' -wThis prints the secret to stdout, making it easy to capture in a variable.
Use It in .zshrc
Section titled “Use It in .zshrc”Export the secret as an environment variable by adding this to ~/.zshrc:
export GITHUB_TOKEN=$(security find-generic-password -a "$USER" -s "GITHUB_TOKEN" -w)Summary
Section titled “Summary”| Task | Command |
|---|---|
| Store | security add-generic-password -a "$USER" -s 'name' -w 'value' |
| Retrieve | security find-generic-password -a "$USER" -s 'name' -w |
| Update | Delete and re-add, or use -U flag to update in place |
| Delete | security delete-generic-password -a "$USER" -s 'name' |
That’s it — no more plaintext secrets in your .zshrc.