-6

I want the read function to print anything but the new line when using in Bash script. I tried the following code, but it does not help. It still prints the new line.

Minimal reproducing code:

#!/bin/bash
stty -echonl
read -e entered

PS. I know I could read characters one by one using read -n1, but this is not the way I would want to use.

14
  • 4
    By default the bash read command does not print anything, it just reads. If your read prints something then it is not the bash builtin read. What do you see if you type command -V read? Commented Jul 4 at 10:13
  • @RenaudPacalet, I see read is a shell builtin. How to use Bash builtint read? Commented Jul 4 at 10:56
  • What exactly is wrong with read -n1 (or, even better, read -rsN1)? Commented Jul 4 at 11:44
  • 5
    You have to edit your question to clarify what you mean by I want the read function to print anything but the new line since read doesn't print anything. I wonder if in your real code you have a subsequent line like echo "$entered" that's printing a newline and you think that entered contains the newline? Please show a minimal reproducible example that we can copy/paste/execute to reproduce whatever problem you're asking for help with. Commented Jul 4 at 12:40
  • 3
    @SergeyBelenkov type read x <<<7 then hit Enter. Did you see anything other than the read x <<<7 that you typed displayed on your terminal? No because read doesn't print anything. Commented Jul 5 at 18:03

2 Answers 2

1

Even though single-character read's are not what the OP wanted, they do filter keypresses quite easily:

text=""
while read -rsN1 char; do
    case "$char" in
        $'\r' | $'\n') break;;
        $'\x7F') text="${text%?}"; echo -n $'\b \b';;
        *) text+="$char"; echo -n "$char";;
    esac
done
echo " [Text entered: '$text']"

The code above filters CR, LF, and DEL — at the cost of reimplementing their effects manually.

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, I know how it could work. I've done something like that in one of a script from my library github.com/sergeniously/shmart/blob/master/core/input.sh
-2

echo entered | awk '{printf "%s", $1}'

maybe?

1 Comment

AFAICS the OP needs newlines filtered out while the user types, not after the variable gets assigned.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.