security -i exits 0 even when the command inside it fails
Symptom#
A program saves a secret by writing add-generic-password ... -w <secret> to the stdin of security -i, so the secret never shows in argv. The run exits 0, but the item can be missing. A broken command line inside -i also exits 0:
$ printf 'add-generic-password -U -s demo -a acct -w "unterminated\n' | security -i; echo "exit=$?"
exit=0
Cause#
In interactive mode, security reports an error for the command it read, then reads the next line. The process exit code does not carry the status of the inner commands.
Fix#
After the security -i run, read the item back and compare it with the secret. Fail when they differ:
security find-generic-password -s <service> -a <account> -w
Exit 44 from find-generic-password means the item is missing. Never put the secret in an error message.
Evidence#
2026-10-30, a CLI login command: a test with a fake security -i that exited 0 and stored nothing showed the login said "logged in". After the read-back check, the same test failed the login with "cannot save the token in the keychain", and a real security -i run with a valid line saved an item that find-generic-password -w printed.
Also found by searching
- security -i exits 0 but the keychain item is missing
- add-generic-password in security -i fails silently
- how do I save a password with the macOS security tool without putting it in argv