9

I copied the below code from some random source to my terminal and ran:

while sleep 1;
  do tput sc;
  tput cup 0 $(($(tput cols)-29));
  date;
  tput rc;
done &

The code is to show a running clock at the top right corner of the terminal. The snippet worked very well and exactly did what I wanted it to, but now I just want to end this loop and get rid of the clock.

Also, I need to understand the above code. I've some idea, as I know what tput command does, but still there're many dots which I'm not able to connect.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
  • 1
    You can run jobs in your session to list active background jobs and then put it to foreground by typing fg <job number>. After type Ctrl+C to stop this infinite loop. This scenario is working only in terminal that run snippet. – Yurij Goncharuk Apr 30 '19 at 20:48
  • Thank you very much, a very clean way of getting rid of the loop. This should become the accepted answer. – Kartik Chauhan Apr 30 '19 at 20:54
  • You are welcome! I put it as answer bellow. – Yurij Goncharuk Apr 30 '19 at 20:56
  • 1
    Note that simply closing the terminal window will also terminate all running jobs attached to it. – trlkly Apr 30 '19 at 21:32
  • You have two questions here. Can you split the 2nd, to a new question. – ctrl-alt-delor Apr 30 '19 at 21:43
  • 1
    That's nothing-- I once foolishly ran a background job that spawned itself twice. Nearly crashed the entire system (mainframe) with the number of jobs that tried to run concurrently! – Carl Witthoft May 01 '19 at 13:56

1 Answers1

15

You can run jobs command in your session to list active background jobs and then put them to foreground by typing fg <job number>. Then type Ctrl+C to stop this infinite loop.

This scenario is working only in terminal that run snippet.


Explanation:

tput sc - save cursor position.

tput cup 0 $(($(tput cols)-29)) - move cursor to position 0 of Y axis and (count of screen columns minus 29) of X axis.

date - just print current date.

tput rc - restore cursor position.

while sleep 1; ... do ... ; done - loop with delay of 1 second.

Type help while to know more about while loop in shell and follow to man 1 tput or tldp tput doc to know how tput works.