How do you safely read a secret or password in a script?
IntermediateConceptVariables, quoting and expansions
Answer
read -rsp 'DB password: ' DB_PASS; echo
-s disables echo, -p prints a prompt. In automation there is no terminal, so read from a file with tight permissions or a secrets manager:
DB_PASS=$(< /run/secrets/db_password) # Docker/K8s secret file
DB_PASS=$(aws secretsmanager get-secret-value --secret-id prod/db \
--query SecretString --output text)
Never pass secrets as command-line arguments (visible in ps and /proc/PID/cmdline), never echo them, and turn off set -x around them.
More on Variables, quoting and expansions
What are the rules for assigning variables in Bash?BeginnerWhat is the difference between single quotes, double quotes and `$'...'`?BeginnerWhy should you almost always quote variable expansions? Show what goes wrong.BeginnerExplain the difference between `"$@"`, `"$*"`, `$@` and `$*`.IntermediateWhat do `${var:-default}`, `${var:=default}`, `${var:+alt}` and `${var:?msg}` do?IntermediateHow do you strip prefixes and suffixes with parameter expansion?Intermediate