This is my current read operation that works okay but I'd like to shorten:

echo "Please save your DB root password:" && read -s dbrp
echo "Please save your DB user password:" && read -s dbup

This is how I've tried to shorten it and quite failed (the prompt is important for me):

echo "Please save your DB passwords (root, then non-root):" && read -s dbrp && echo "\n" && read -s dbup

It is already in one line as I desired but I'm not comfortable with it because:

  1. There are two read -s commands instead just one.
  2. I must use echo /n to break row while I would want break without that.

Anything could be done to improve that?


I had a mistake using echo there (besides for adding \n. As read has its own prompt adding option:

read -sp "What's your DB root password?" dbrp
read -sp "What's your DB user password?" dbup

If you're willing to change the name of your variables and make your code bash-specific (-s is available in zsh and bash; -p for prompt is bash only, zsh uses read 'var?prompt' like in ksh for that), I think the following is elegant and straightforward:

for arg in root user; do
    IFS= read -rsp "Please enter your $arg password: " "dbr_$arg"

The result should have your passwords in variables $dbr_user and $dbr_root.

Note that you need the -r and IFS= to allow the user to have backslashes or leading/trailing spaces or tabs in their password.

The zsh equivalent:

for arg (root user) IFS= read -rs "dbr_$arg?Please enter your $arg password: "
  • Hmm, using the read prompt via -p is cool. Argument $1 is another argument domain, so I guess the read should relate to $2 and $3. – Arcticooling Jan 16 '18 at 10:08
  • IFS? rsp? What is the meaning of these? – Arcticooling Jan 16 '18 at 10:14
  • @Arcticooling, see Understand "IFS= read -r line"? – Stéphane Chazelas Jan 16 '18 at 10:15
  • @Arcticooling rsp is just the combination of r,s and p. It is just the same as read -r -s -p, and for these individual letters you can refer to the man pages – Weijun Zhou Jan 16 '18 at 13:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.