Storing and retrieving passwords in bash scripts from the macOS keychain

It's often convenient to store a password in the macOS system keychain and retrieve it inside a shell script.

Here's the bash command for setting a password:

security add-generic-password -s "Keychain item name here" -a "username here" -p

Then enter your password when prompted.

After you run this once, you can retrieve the password in a script like this:

PASSWORD=`security find-generic-password -s "Keychain item name here" -a "username here" -w`

You can then use $PASSWORD whenever you need the password in your script.


🌟 Was this page helpful? Please let me know with this quick, 3 question survey.