Some useful shell commands

20 Jul

Get the CPU Usage: top -b -d1 -n1|grep -i “Cpu(s)”

top -b -d1 -n1|grep -i “Cpu(s)”|cut -d’:’ -f2 |awk -F’,’ ‘{print $1 $2,$4}’

Result:  ===0.0%us  0.0%sy 100.0%id

Get the Memory Usage: top -b -d1 -n1|grep -i “Mem:”| cut -d’:’ -f2

Result: ===33013712k total,  1131848k used, 31881864k free,   163056k buffers

If you want to remove the last letter from one line

top -b -d1 -n1|grep -i “Mem:”| cut -d’:’ -f2 | awk -F’,’ ‘{print $1}’|awk -F’ ‘ ‘{print $1}’ |sed -e ‘s/k//’

******************All scripts*************************************************************

Collect the CPU and memory usage and save them into a csv file


for((; ;)) do
NOW=$(date +”%m-%d-%y-%T”)
timestamp=$(date +”%m-%d-%y”)
#top -b -d1 -n1|grep -i “Cpu(s)”|cut -d’:’ -f2 |awk -F’,’ ‘{print $1}’ | awk -F’%’ ‘{print $1}’
cpu_usage=` top -b -d1 -n1|grep -i “Cpu(s)”|cut -d’:’ -f2 `
usr_cpu=`echo $cpu_usage | awk -F’,’ ‘{print $1}’ | awk -F’%’ ‘{print $1}’`
sys_cpu=`echo $cpu_usage | awk -F’,’ ‘{print $2}’ | awk -F’%’ ‘{print $1}’`
idl_cpu=`echo $cpu_usage | awk -F’,’ ‘{print $4}’ | awk -F’%’ ‘{print $1}’`
echo “$NOW $usr_cpu $sys_cpu $idl_cpu” >> $cpu_file

# memory usage top -b -d1 -n1|grep -i “Mem:”| cut -d’:’ -f2 | awk -F’,’ ‘{print $1}’|awk -F’ ‘ ‘{print $1}’
mem_usage=`top -b -d1 -n1|grep -i “Mem:”| cut -d’:’ -f2`
total_mem=`echo $mem_usage| awk -F’,’ ‘{print $1}’|awk -F’ ‘ ‘{print $1}’`
used_mem=`echo $mem_usage| awk -F’,’ ‘{print $2}’|awk -F’ ‘ ‘{print $1}’ |sed -e ‘s/k//’`
free_mem=`echo $mem_usage| awk -F’,’ ‘{print $3}’|awk -F’ ‘ ‘{print $1}’ |sed -e ‘s/k//’`
buffer_mem=`echo $mem_usage| awk -F’,’ ‘{print $4}’|awk -F’ ‘ ‘{print $1}’ |sed -e ‘s/k//’`
echo “$NOW $total_mem $used_mem $free_mem $buffer_mem”>> $mem_file

sleep 5

Leave a comment

Posted by on July 20, 2012 in Uncategorized


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: