Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux "echo -n" not being flushed

Tags:

linux

bash

I have the following code:

while ...
  echo -n "some text"
done | while read; do
  echo "$REPLY" >> file
done

but echo works only when used without "-n" flag. looks like when using -n, the output is not flushed/read by next while loop

How can I make sure that "some text" will be read even when not followed by EOL?

like image 870
optivian Avatar asked May 01 '18 08:05

optivian


People also ask

How do I print N in bash?

Printing Newline in Bash The most common way is to use the echo command. However, the printf command also works fine. Using the backslash character for newline “\n” is the conventional way.

What is echo N?

The echo command uses the following options: -n : Displays the output while omitting the newline after it. -E : The default option, disables the interpretation of escape characters. -e : Enables the interpretation of the following escape characters: \\: Displays a backslash character (\).

How do I print echo without newline?

Using printf it's easy—just leave off the ending \n in your format string. With echo, use the -n option.

How do you echo a new line in shell script?

Using echo Note echo adds \n at the end of each sentence by default whether we use -e or not. The -e option may not work in all systems and versions. Some versions of echo may even print -e as part of their output.


2 Answers

You can't distinguish between

echo -n "some text"

and

echo -n "some t"
echo -n "ext"

so you need some kind of delimiting rule. Usually EOL is used for that. read supports custom delimiter via -d or can split based on number of chars via -n or -N. For example you can make read fire on each symbol:

echo -n qwe | while read -N 1 ch; do echo $ch; done
like image 166
Uprooted Avatar answered Oct 04 '22 02:10

Uprooted


The workaround would be (following original example):

while ...
  echo -n "some text"
done | (cat && echo) | while read; do 
  echo "$REPLY" >> file
done

This will append EOL to the test stream & allow read to read it. The side effect will be an additional EOL at the end of stream.

like image 31
Maciej Avatar answered Oct 04 '22 03:10

Maciej