Home > database >  How to overwrite multiple outputted lines from a bash script into the terminal
How to overwrite multiple outputted lines from a bash script into the terminal

Time:10-12

I have a kubernetes command kubectl get pods which prints to the terminal this output

 NAME                          READY   STATUS    RESTARTS   AGE
redis-cart-74594bd569-ffrhk   1/1     Running   0          40m

I want this command to run repeatedly every two seconds in a bash script. However, I want the output to overwrite the last input.

Currently, I can get it to overwrite one line (the first outputted line) by using a carriage return. But it doesn't overwrite the second line.

How can I overwrite previously outputted text from my bash script?

By script looks like this atm

#!/bin/bash

variable=$(kubectl get pods)

while true
do
    variable=$(kubectl get pods)
    echo -ne "$variable" "\r"
    sleep 2
done
exit

CodePudding user response:

Add clear command to the loop:

#!/bin/bash

variable=$(kubectl get pods)

while true
do
    variable=$(kubectl get pods)
    clear
    echo -ne "$variable" "\r"
    sleep 2
done

But, you can use watch or -w to get a similar result without a special script.

CodePudding user response:

try watchto refresh output ...

watch kubectl get pods

To end the process you can use CTRL C or look for the process via ps or pgrepand send a SIGINT like pgrep watch kubectl | xargs kill -1.

  •  Tags:  
  • bash
  • Related