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.

6
  • 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. Apr 30, 2019 at 20:48
  • Thank you very much, a very clean way of getting rid of the loop. This should become the accepted answer. Apr 30, 2019 at 20:54
  • You are welcome! I put it as answer bellow. Apr 30, 2019 at 20:56
  • 1
    Note that simply closing the terminal window will also terminate all running jobs attached to it.
    – trlkly
    Apr 30, 2019 at 21:32
  • 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! May 1, 2019 at 13:56

1 Answer 1

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.

4
  • I still would like to know how did the code do what it did. Apr 30, 2019 at 20:58
  • @KartikChauhan I put some explanation also. Apr 30, 2019 at 21:14
  • @KartikChauhan You are right! Thank's! I've just fixed this. Apr 30, 2019 at 21:20
  • 3
    kill %1 (or a different number if there are multiple jobs) is an alternative to fg + Ctrl-C Apr 30, 2019 at 23:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .