3

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?

1 Answer 1

4

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.

2
  • 6
    With bash, use read -p 'some prompt' to provide a prompt for the user. The script in the question prints the prompt to standard output. Interactive prompts should be printed to standard error, which read -p does. Also, login is a poor choice of name for the function as it 1) does not log in, and 2) it overrides the existing login utility's name. Commented Feb 10, 2020 at 12:52
  • @Kusalananda the name login was just a testing one, I usually name my functions starting with f__. Thanks! Commented Feb 11, 2020 at 7:43

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.