Bash: Fix Echo After printf Not Displaying in New Line

bashechonewlinesprintf

I have a code which will use printf and then echo command. As per my understanding echo will by default come in new line, but not happening when it is used after printf. Below is the code:

#!/bin/bash
function login
{
  printf "\n%s" "Please enter ${1} password: "
  read -s passcode
}
for i in root admin; do login $i; done
echo "just something"

In this code "\n%s" is important as I might be using multiple users in that loop. The output is like below:

[root@host ]# /tmp/test.sh

Please enter root password:
Please enter admin password: just something
[root@host ]#

I know by putting a echo "" after the loop will simply fix and create a new line, but I would like to know why while looping with printf it's working and why not with echo afterwards?

Best Answer

echo outputs a newline at the end of the string, not at the beginning.

printf interprets \n as a newline, but \n%s prints the newline before the rest of the output, not after it.

And since with read -s, we suppress the terminal local echo of what is being typed, when the user presses Enter, that also suppresses the CRLF echo.

In any case, the syntax to read the password should be IFS= read -r passcode, or it wouldn't work properly if the password contained backslash or $IFS characters.

Related Question