2

current code:

echo -n "password: "
read -es password
echo -n "ok"

behavoir in linux:

password: ok

Can we make it like:

password:
ok

thanks, wxie

The following will work:

read -p "password: " -es password
echo
echo "ok"
wxie
  • 513
  • 7
  • 10

4 Answers4

5

Maybe:

read -p "password: " -es password
printf "\n ok \n"
2

If you want a newline before the OK, this should do it:

echo -e "\nok"

The -e enables interpretation of the backslash codes.

Greg Tarsa
  • 1,622
  • 13
  • 18
1

From echo's man page: -n do not output the trailing newline. Try it without the option.

  • Thanks, but you need try it first. -n is intended for doing password: xxx(cr). Without -n the output would be password: (newline). – wxie Apr 01 '16 at 05:28
  • @wxie, on bash version 3 and bash version 5, `help read` describes the `-n` option for `read` to be: "If -n is supplied with a non-zero NCHARS argument, read returns after NCHARS characters have been read." So, `read -n` does not seem to relate to passwords and newlines as you say. – nishanthshanmugham Sep 25 '22 at 19:35
  • @wxie, I see you may be talking about `echo -n`, not `read -n`. Please ignore my previous comment. – nishanthshanmugham Sep 25 '22 at 19:36
0

We can use \n as a line separator in printf, there is an extra line for padding after "ok" which you can remove

printf "password: " && read -es password && printf "\n\nok\n"

If you are saving a password this way it would still be contained in the variable $password in plain text, the string below would print it openly.

printf "$password"

Your code sample uses echo and should be using printf, there are articles on echo's POSIX compliance, echo could work like Greg Tarsa points out, but not all versions are built with switch options like -e or -n.

I find it readable to use printf, also other "languages" have similar commands such as PRINT, print, println, print() and others.

If you need to use echo you could

echo -n "password: " && read -es password && echo -e "\nok\n"
knueser
  • 357
  • 3
  • 14
Stef
  • 87
  • 9