How to show and update echo on same line

前端 未结 6 1319
陌清茗
陌清茗 2020-11-27 11:27

I have the following in Bash (In Linux)

for dir in Movies/*
do
  (cd \"$dir\" && pwd|cut -d \\/ -f5|tr -s \'\\n\' \', \' >> ../../movielist &am         


        
6条回答
  •  伪装坚强ぢ
    2020-11-27 12:11

    The rest of answers are pretty good, but just wanted to add some extra information in case someone comes here looking for a solution to replace/update a multiline echo.

    So I would like to share an example with you all. The following script was tried on a CentOS system and uses "timedatectl" command which basically prints some detailed time information of your system.

    I decided to use that command as its output contains multiple lines and works perfectly for the example below:

    #!/bin/bash
    while true; do
      COMMAND=$(timedatectl) #Save command result in a var.
      echo "$COMMAND" #Print command result, including new lines.
    
      sleep 3 #Keep above's output on screen during 3 seconds before clearing it
    
      #Following code clears previously printed lines
      LINES=$(echo "$COMMAND" | wc -l) #Calculate number of lines for the output previously printed
      for (( i=1; i <= $(($LINES)); i++ ));do #For each line printed as a result of "timedatectl"
        tput cuu1 #Move cursor up by one line
        tput el #Clear the line
      done
    
    done
    

    The above will print the result of "timedatectl" forever and will replace the previous echo with updated results.

    I have to mention that this code is only an example, but maybe not the best solution for you depending on your needs. A similar command that would do almost the same (at least visually) is "watch -n 3 timedatectl".

    But that's a different story. :)

    Hope that helps!

提交回复
热议问题