A few piped Linux commands and short scripts

Here’s a couple of bash and Perl scripts, and piped Linux commands that I’ve found to be useful. Let me know if you are having trouble with any of these. Your mileage may vary depending on your version of bash and Perl.

Current CPU Usage in percent (bash):

You can get the same info from other tools like htop and mpstat, but they might not be installed by default.

# Linux
top -bn 10 -d 0.01 | grep '^Cpu.s.' | tail -n 1 | awk '{cpu_use = $2 + $4 + $6 ; printf("%.2f\n", cpu_use)}'
# Solaris
top -bn 10 -d 0.01 | grep 'CPU states' | awk -F ' |%' '{cpu_use = $7 + $11 ; printf("%.2f\n", cpu_use)}'

Current RAM Usage in percent (bash):

# Linux
free -m | awk 'FNR == 2 { ratio = $3 / $2 ; ram_use = ratio * 100 ; printf("%.2f\n", ram_use)}'
# Solaris
top -bn 10 -d 0.01 | grep 'Memory' | awk -F \" |G\" '{used = $2 - $6 ; ram_use = (used / $2) * 100 ; printf("%.2f\n", ram_use)}'

System Usage (perl):

my $linuxCPUpct = "top -bn 10 -d 0.01 | grep '^Cpu.s.' | tail -n 1" ;  # CPU usage
my $linuxRAMpct = "free -m | grep 'Mem:'" ;  	# RAM usage
my $linuxROOTpct = "df -hl / | grep '/'" ;  	# / disk usage
my $linuxHOMEpct = "df -hl /home | grep 'home'" ;  # /home disk usage

my $cpu_res = "" ; my $ram_res = "" ; my $root_res = "" ; my $home_res = "" ;

my @CPU_parse = split ( ',', `$linuxCPUpct` ) ;
my @RAM_parse = split ( ' ', `$linuxRAMpct` );
my $linuxROOT = (`$linuxROOTpct` =~ /(\d+)%/img)[0] ;
my $linuxHOME = (`$linuxHOMEpct` =~ /(\d+)%/img)[0] ;

$ram_res = sprintf("%.2f", $RAM_parse[2] / $RAM_parse[1] * 100.0 ) ;
$cpu_res = sprintf("%.2f", substr($CPU_parse[3], 0, -3)) ;
$root_res = sprintf("%.2f", $linuxROOT) ;
$home_res = sprintf("%.2f", $linuxHOME) ;

print ("CPU Usage: $cpu_res\n") ;
print ("RAM Usage: $ram_res\n") ;
print ("/ Usage: $root_res\n") ;
print ("/home Usage: $home_res\n") ;

Reset Password expiry script (bash):

Perhaps not the best idea security wise, but it’s handy when you’re lazy.

pwd_age=$(grep "username:" /etc/shadow | cut -d: -f 3)
echo $pwd_age;
now=$(( $(date +%s) / 3600 / 24 ))
echo $now;
age_at_expiry_date=$(( $now + 90 - $pwd_age))
echo $age_at_expiry_date;
chage username -M $age_at_expiry_date

Multi-Ping script (bash):

Self-explanatory. Pass the IPs as arguments to mping.

# mping: Multiple ping
# Script to ping multiple units. Each unit is pinged 4 times.


for args
        ping -c 4 ${arrArgs[$i]}
        echo -e "\n"

And a few words of wisdom…


Wipe your HDD, flash Linux from USB and partition Windows (Free tools)

Every once in a while, after doing a clean install of Windows, I find the need to partition one of my drives and install Linux. Occasionally, I’ve had to “nuke” my drive, because Windows simply wouldn’t boot.

While that sounds all fine and not that complicated to do, there’s a couple of handy tools I’ve used time and time again to do all this. Partitioning Windows active drives is a bit of a pain, too. Here are a few free tools that might help you out.


Nuke your HDD from USB: DBan
Homepage: http://www.dban.org/
Direct Download: http://sourceforge.net/projects/dban/files/dban/dban-2.3.0/dban-2.3.0_i586.iso/download
From the site’s homepage:

DBAN is free erasure software designed for the home user. It automatically deletes the contents of any hard disk that it can detect. This method prevents identity theft before recycling a computer. DBAN is also a commonly used solution to remove viruses and spyware from Microsoft Windows installations.

From what I’ve read, DBan has been around for a few years. It was recently acquired by a paid competitor, but DBan itself is still free.
You’ll have to install it to a flash drive and then boot via USB from your BIOS.

Create a bootable Linux USB Drive (from Windows): LiLi USB Creator
Homepage: http://www.linuxliveusb.com/
Direct download: http://www.linuxliveusb.com/downloads/?stable
LiLi stands for Linux Live. This is a Windows tool that will install any .iso file with a Linux kernel onto your USB drive.
I’ve found it to be the easiest to use, although there are many alternatives.

Partitioning Windows (from Windows): MiniTool Partition Wizard Free

Homepage: http://www.partitionwizard.com/free-partition-manager.html
Direct download: http://download.cnet.com/MiniTool-Partition-Wizard-Free/3001-2094_4-10962200.html?hlndr=1
I’ve used EaseUs Partition Master (free edition) in the past, and I’ve found it to be a little too bulky to my liking. More recently, I tried this software alternative, and it worked flawlessly. Just install and the rest is pretty straightforward.

Getting the System Time in C (Function)

It has been a while since I’ve posted a tutorial, so I figured I would go over a simple example on how to write a function to return the system time in C.

The code below has only been tested on a handful of UNIX systems (RHEL 6.5, SLES 10 and Solaris 10), therefore I can’t guarantee the output on Windows systems (but it really should, considering time.h is a part of the Standard C library).

Overall, it is really straightforward and mostly self-explanatory if you’re at all familiar with C, and my solution is partially borrowed from a post on StackOverflow (with a few enhancements).

#include <time.h>
#include <stdio.h>
#include <stdlib.h>

const char * getSystemTime()
    struct timeval tp;
    struct tm *t;
    char *current_time;
    time_t curtime;    
    gettimeofday(&tp, 0); //Pass tp to library function gettimeofday()
    curtime = tp.tv_sec;
    t = localtime(&curtime);
    current_time = (char *) malloc(sizeof(char) * 18);
                         t->tm_hour, t->tm_min, t->tm_sec, tp.tv_usec/1000);
    return current_time;

int main (void)
    printf("%s\n", getSystemTime());


The time format is important to note here:

"%02d:%02d:%02d:%04d", t->tm_hour, t->tm_min, t->tm_sec, tp.tv_usec/1000

This essentially translates to the following time format:

12:51:12:0491 | | | |-> Milliseconds (4 digits) | | |----> Seconds (2 digits) | |-------> Minutes (2 digits) |----------> Hours (2 digits)

For more info the time.h library in C, check out the links below:
GNU: Elapsed Time
cplusplus.com: C Library time.h
cplusplus.com: C Library struct tm


PuTTY / Terminal Color Schemes

Earlier today, I was setting up my PuTTY environment at my university. PuTTY’s user interface lends itself to a number of hurdles.

Although it has a decent amount of customizability, the UI makes each task overly complicated. For instance, PuTTY makes editing the color scheme absolutely tedious.

With a glimmer of hope, I searched Google for a more elegant solution to edit my PuTTY color scheme without having to deal with PuTTY itself.

A post on StackOverflow, at the bottom of the answers, indicated the solution I was longing for:

4bit Terminal Color Scheme Designer (ciembor.github.io/4bit/)

The title is self-explanatory, it’s an easy to use Terminal Color Scheme Designer.

Steps for PuTTY on Windows:

  • Customize the Color scheme how you see fit
  • Click on ‘Get Scheme’ in the upper right
  • Export Scheme to a PuTTY configuration File
  • Save file as .reg (Registry Extension)
  • Optional: If you are not trying to change the color scheme for the PuTTY ‘Default Settings’ profile, you will have to edit: [HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions\Default%20Settings]
  • Execute the .reg file (and accept the Registry Editor warning*)
  • Done!

As you may have noticed, this tool also works with many UNIX based terminals. I haven’t gotten to try it in Linux/UNIX environments, but please leave some feedback below if you run into any issues. I’ll see what I can do to help!

Big thanks to Maciej Ciemborowicz for creating this tool!

*Warning Note: I am not responsible for any broken Registries/Terminals that may be caused. Please read, understand and review files carefully before allowing them to edit your Registry.

Edit (2014/09/27):
For anyone wondering, the 4bit Terminal Color Scheme Designer supports the following terminal environments:

  • xterm / aterm / rxvt / urxvt (.Xresources)
  • gnome terminal (shell)
  • guake (shell)
  • konsole / yakuake (*.colorscheme)
  • xfce4 terminal (terminalrc)
  • iTerm2 (*.itermcolors)
  • mintty (.minttyrc)
  • putty (*.reg)
  • terminator (config)