Monday, August 9, 2010

Time in ps command

Today I learned something that I always thought was right when it was actually wrong.
It is the TIME in ps command.

$ ps ux
USER       PID %CPU %MEM   VSZ  RSS TTY      STAT START   TIME COMMAND
user1      991  0.0  2.4 19282 9076 ?        S    15:05   0:00 kdeinit: kded    
user1      780  0.1  1.0  5890 3044 ?        S    16:39   0:01 artsd -F 10 -S 40


The TIME in above output does not mean the total time since the process actually started. But it actually means the total time the process was processing. In other words, it is the sum of all durations the process was actually on the processor(s).

It was a true serendipity indeed!

Monday, March 1, 2010

Work like a UNIX Shell Scripting pro - Use AWK and Sed

Unix may seem little daunting at the beginning when you start writing a shell script to automate a task. But there are two UNIX tools that can save you from some real headache.

1. AWK
2. Sed

You don't have to learn them completely to start using them. But in case you are interested in learning more about them just follow the above links. There are couple of commands that you can start using right away to write good shell scripts. You will have to remember one rule in UNIX that you can pass the output of one command to another command by using a pipe "|"

Below are some of the AWK and Sed which I use quite often to accomplish various tasks:

Get a particular field from a line of text, one line at a time, till you reach the EOF:

ps -ef | awk '{print $2}'



Monday, January 4, 2010

Execute multiple remote commands using SSH

Suppose you want to execute multiple commands on a remote server without going to that server and actually typing the commands there.

For instance you can get the pid of a process and then kill it using ssh as under:

ssh admin@remote << HEREDOC
KILLPID=`ps -ef | grep firefox | awk '{print $2}'`
kill -9 $KILLPID
HEREDOC

Explaination:

First of all, you need to know what a heredoc is. Using a heredoc also takes away the complexity associated with escaping special characters in a command (ticks and quotes in our example).

KILLPID=`ps -ef | grep firefox | awk '{print $2}'`

will define a shell variable KILLPID and assign PID of firefox process to it.

kill -9 $KILLPID

ofcourse we could have accomplished this using xargs but above example demonstrates how to remotely fire multiple commands in single SSH session.

In case you are curious how xargs would have served the purpose:

ssh admin@remote << HEREDOC
KILLPID=`ps -ef | grep firefox | awk '{print $2}' | xargs kill -9`
HEREDOC

Once we have the PID in a variable, we can kill it using kill -9 command

Happy SSHing.