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.

  • 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
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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.