Simple Programming Examples


Bash Script with grep and cut

The "ps aux" command shows a lot of output:

It goes on for several pages, ending like this:

Suppose I want to see only the Process IDs for "bash" processes.

I can filter the output for lines containing "bash" with grep like this:

ps aux | grep "bash"
This shows the "bash" lines I want, but also a "grep bash" line I don't want.

To remove the unwanted line, I use grep again with the -v switch to remove matching lines:

ps aux | grep "bash" | grep -v "grep bash"
Now I have only the lines of interest.

To retain only the Process IDs, I use cut with a delimiter of " " and output the second field:

ps aux | grep "bash" | grep -v "grep bash" | cut -d " " -f 2
This fails because there are six spaces after "root", so the second field is just another space.

Just trying various values, I find that the seventh field contains the Process ID:

ps aux | grep "bash" | grep -v "grep bash" | cut -d " " -f 7

I can put this into a file named psbash

Making the file executable and running it shows that I now have a "psbash" command that shows only PIDs from "bash" processes.

This program has some limitations. If users othe than "root" open bash shells, it may not find them because there's a different number of spaces separating the fields. Process IDs with a length other than 4 might also lead to failure. A better script could fix that, but for this example I'll stop here.


Python Script for Port Scanning

Here's the example from the textbook, a Python script that scans one port:

Making the file executable and running it shows that it works:


C Program

Here's the example from the textbook, a C program that takes one command-line argument (a name) and says Hello to that name:

Compiling and running it shows that it works:

Posted: 9-15-15