bash: How to echo strings at the same position bash: How to echo strings at the same position unix unix

bash: How to echo strings at the same position


There's another option, to position the cursor before you write to stdout.

You can set x and y to suit your needs.

#!/bin/bashy=10x=0i=0while [ $i -lt 20 ]; do    tput cup $y $x    echo ''    echo ''    echo ''    echo '============== current time ==============='    echo $i    echo '==========================================='    echo ''    curl -i http://www.example.com/index?key=abceefgefwe    i=$((i+1))done


You could add a clear command at the beginning of your while loop. That would keep the echo statements at the top of the screen during each iteration, if that's what you had in mind.


When I do this sort of thing, rather than using curses/ncurses or tput, I just restrict myself to a single line and hope it doesn't wrap. I re-draw the line every iteration.

For example:

i=0while [ $i -lt 20 ]; do  curl -i -o "index$i" 'http://www.example.com/index?key=abceefgefwe'  printf "\r==== current time: %2d ====" $i  i=$((i+1))done

If you're not displaying text of predictable length, you might need to reset the display first (since it doesn't clear the content, so if you go from there to here, you'll end up with heree with the extra letter from the previous string). To solve that:

i=$((COLUMNS-1))space=""while [ $i -gt 0 ]; do  space="$space "  i=$((i-1))donewhile [ $i -lt 20 ]; do  curl -i -o "index$i" 'http://www.example.com/index?key=abceefgefwe'  output="$(head -c$((COLUMNS-28))) "index$i" |head -n1)"  printf "\r%s\r==== current time: %2d (%s) ====" "$space" $i "$output"  i=$((i+1))done

This puts a full-width line of spaces to clear the previous text and then writes over the now-blank line with the new content. I've used a segment of the first line of the retrieved file up to a maximum of the line's width (counting the extra text; I may be one off somewhere). This would be cleaner if I could just use head -c$((COLUMNS-28)) -n1 (which would care about the order!).