Interesting Shell Scripts

Here few interesting shell scripts are provided.
These can be used for linux systems. It is tested in Ubuntu 12.04 LTS systems.

Flush the system cache memory

If you are running a C/C++ based application, and memory is allocated at heavy rate, system puts an optimal logic for memory management. You can verify system memory using free -k or sar -r 2 10 commands. You will observe system memory goes high. Look like there is some memory leak by C/C++ application. However in reality this may not be true. Even if memory leak is not there, still you will observe free memory in system reduces. Reason, some memory on freeby application is treated as cache memory by linux OS (mainly buffers). If you really want to see memory leak is there or not, run below script which will flush the cache memory time to time and using sarcommand you can see system used memory (RAM space) is within a range.

Warning: While you run this script, system performance may reduce as you are flushing canhe memory which OS would have used in next requirement.

for i in `seq 2 $max`
echo 3 > /proc/sys/vm/drop_caches
echo 'Cache memory flushed after ' $loop_sleep ' seconds'
sleep $loop_sleep
Print socket counts present in system

Sometimes you may need to print sockets (tcp, udp, your application) releated socket counts. You can make use of below scripts. In this case application name is MSIP.

for i in `seq 2 $max_loop`

all_socks=$(netstat -anp | wc -l)
echo "Total sockets " $all_socks

all_msip_socks=$(netstat -anp | grep MSIP | wc -l)
echo "Total MSIP sockets " $all_msip_socks

all_tcp_socks=$(netstat -anp | grep tcp | wc -l)
echo "Total TCP sockets " $all_tcp_socks

all_udp_socks=$(netstat -anp | grep udp | wc -l)
echo "Total UDP sockets " $all_udp_socks

echo "------------------------------------------------------------------------"

sleep 1

Deleting semaphore, shared memory blocks and message queues

Sometimes you need to clear semaphore, shared memory blocks and message queues.
You can use below script to clear semaphore, shared memory blocks and message queues.

IPCS_S=`ipcs -s | egrep -i "0x[0-9a-f]+.*[0-9]+" | grep kamal | cut -f2 -d" "`
IPCS_M=`ipcs -m | egrep -i "0x[0-9a-f]+.*[0-9]+" | grep kamal | cut -f2 -d" "`
IPCS_Q=`ipcs -q | egrep -i "0x[0-9a-f]+.*[0-9]+" | grep kamal | cut -f2 -d" "`

for id in $IPCS_M; do
ipcrm -m $id;

for id in $IPCS_S; do
ipcrm -s $id;

for id in $IPCS_Q; do
ipcrm -q $id;