Thursday, May 8, 2014

The watch command

A very nice command to watch something in linux

watch -n1 "sudo netstat -antp | grep -i listen"

this will show you on the screen the output of sudo netstat -antp | grep -i listen every "1" second. 

Screen command in Linux

Its the end of your day at work and at the last moment , you were asked to run a script to generate a report. This script would take around 30 mins to run and you only have 5 mins to catch the bus that takes you home.. what do you  do???

One option is for you to run the script as a backgroup nohup process and redirect logs to a file, get back home and look at the logs.

Screen is the other thing that can help you here. With screen you can leave the script running on the machine and get back home and connect back to see the output terminal instead of the log file. 

How to use screen:

- screen -S "screen-name"                  to start a screen

eg: screen -S 70mm 

This will start the screen-name with 70mm in it.


- screen -ls                                        to list all screens
There is a screen on:
        15902.70mm      (Attached)
1 Socket in /var/run/screen/S-sanjeevn.

Attached means that you are right now inside the screen itself i.e: connected to the screen. You can start runnign the script here wil make it run continusoulsy

example:

while true
> do
> echo "Press [CTRL+C] to stop.."
> sleep 1
> done
Press [CTRL+C] to stop..
Press [CTRL+C] to stop..
Press [CTRL+C] to stop..

- ctrl-a-d                                            to detach from a screen

This will detach you form the screen and bring you back to the original terminal

[detached]
["user-name"@greenshot-dl image]

- screen -r "screen-name"                     to connect to a screen name obtained from the above command
eg: 
screen -r 15902.70mm  (obtained form the screen -ls command )

lo and behold the script is still running

Press [CTRL+C] to stop..
Press [CTRL+C] to stop..
Press [CTRL+C] to stop..
Press [CTRL+C] to stop..
Press [CTRL+C] to stop..
Press [CTRL+C] to stop..
Press [CTRL+C] to stop..
Press [CTRL+C] to stop..
Press [CTRL+C] to stop..
Press [CTRL+C] to stop..

- ctrl-d                                               to stop a screen
[screen is terminating]