I want to prompt a user to enter a secret value (for ex: password variable, credit card, some key/token) and would like to see if there's a way to show the last N (lets say 4 characters) of that variable's value.
Ex: Enter your credit card# : 1234567898765432
I can use wrappers for ex stty -echo/echo
to hide what user will enter or use read -s variable
and it'll hide the values but what I'd like is to show only last N (for ex: 4) characters of this variable i.e.
if I say $ echo $mySecretVariable
(not sure if I really have to write a function) then it will echo the value as: ************5432
or your token key value last 4 ends with *******************C5fx
something like that where all the characters will be padded with a *
and only the last N will be shown.
You can use this bash function for masking all but last 4 characters:
mask() {
local r="${1?needs an argument}"
if ((${#r} > 4)); then
r="${r:0: -4}"
echo "${r//?/*}${1: -4}"
else
echo "$r"
fi
}
Then use it as:
mask 1234567898765432
************5432
mask 123
123
mask 123456
**3456