Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show and update echo on same line

Tags:

bash

I have the following in Bash (In Linux)

for dir in Movies/* do   (cd "$dir" && pwd|cut -d \/ -f5|tr -s '\n' ', ' >> ../../movielist &&   exiftool * -t -s3 -ImageSize -FileType|tr -s '\t' ',' >> ../../movielist ) echo "Movie $movies - $dir ADDED!" let movies=movies+1 done 

But I wish to make it so the "echo" shows the following echo on the next line (Not concatenate with the last echo output but replace it) so to make it look like it is updating. Similar to how a progress bar with percent would show on the same line.

like image 470
Luis Alvarado Avatar asked Sep 27 '12 18:09

Luis Alvarado


People also ask

How do you echo without a new line?

The best way to remove the new line is to add '-n'. This signals not to add a new line. When you want to write more complicated commands or sort everything in a single line, you should use the '-n' option. So, it won't print the numbers on the same line.

Does echo append a newline?

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.

How do I print on the same line in Linux?

We can use printf command to display the text to the standard output stream. The output of the command and the next command prompt are on the same line. No newline is printed.

How do I append a line in echo?

This appending task can be done by using 'echo' and 'tee' commands. Using '>>' with 'echo' command appends a line to a file. Another way is to use 'echo,' pipe(|), and 'tee' commands to add content to a file.


1 Answers

Well I did not read correctly the man echo page for this.

echo had 2 options that could do this if I added a 3rd escape character.

The 2 options are -n and -e.

-n will not output the trailing newline. So that saves me from going to a new line each time I echo something.

-e will allow me to interpret backslash escape symbols.

Guess what escape symbol I want to use for this: \r. Yes, carriage return would send me back to the start and it will visually look like I am updating on the same line.

So the echo line would look like this:

echo -ne "Movie $movies - $dir ADDED!"\\r

I had to escape the escape symbol so Bash would not kill it. that is why you see 2 \ symbols in there.

As mentioned by William, printf can also do similar (and even more extensive) tasks like this.

like image 155
Luis Alvarado Avatar answered Sep 21 '22 01:09

Luis Alvarado