Shell scripts

From FoppaWiki

Jump to: navigation, search

Small one liners and scripts for day to day work. Most might not fit your purpose excactly, but should be easy to figure out and alter for your needs.

Oneliner to delete files which are 3+ days old:

# find /files/oldfiles/ -mtime +3 -iname "HELLO.*" -exec rm -f {} \;

Delete all listed dirs in a file:

# for dir in `cat blah.txt`; do echo processing $dir; echo rmdir $dir; done

Small bash script to check if something has read/write, and email if something is not. It's very simple, but the concept works, and can be used for lots of other stuff. This one checks if it can touch a file on all mounts, if it cannot, it sends an email:

#!/bin/bash
for mounts in `df -h | grep -i sd | awk {'print $6'}`; do
touch $mounts/touch-test
if [ $? == 1 ] ; then
echo "$mounts is mounted READONLY" | mail "user@email.com" -s "$mounts is mounted READONLY"
exit 1
else
echo "$mounts is mounted RW"
fi
done

Another if else bash example:

FILECOUNT=`find /data/backup/rsync/ -type f | wc | awk {'print $1'}`
ALERTCOUNT="80"

if [ ! $# == 0 ]; then
 let ALERTCOUNT=$1
fi

if [ "$FILECOUNT" -lt "$ALERTCOUNT" ] ; then
 echo "file count is $FILECOUNT .... terminating rsync, something must be wrong"
else
 echo "backuplol!"
fi

Shell if else elif parameter command line example:

#!/bin/bash

if [ "$1" == "roll" ]; then
        echo "they see me rollin"
elif [ "$1" == "hate" ]; then
        echo "they hatin"
else
        echo "your doing it wrong, type something after $0"
fi

Usable cut example. The following will first use = as delimiter and cut out field 3. Second time we use & as delimiter and cut out field 1. Finally we sort and uniq to get the list.

cat www.foppa.dk-http-access.log | grep ex | grep domain 
94.18.98.145 - - [10/Jun/2011:10:27:24 +0200] "GET /ex/index.php?country=dk&domain=foppa.dk&md5id=sadhkjsdhfkjashdflkjashdkaskjdfhasd HTTP/1.1" 301 507 "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)"

cat www.foppa.dk-http-access.log | grep ex | grep domain | cut -d= -f3 | cut -d\& -f1 | sort | uniq
foppa.dk

Another cut example:

/sbin/ifconfig ${1:-eth0} | grep "inet addr" | cut -d: -f2 | cut -d" " -f1

And the same with awk:

/sbin/ifconfig ${1:-eth0} | awk '/inet addr/ {print $2}' | awk -F: '{print $2}'

Sed in a file:

sed -i -e 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config

How to make a random password from /dev/random in a shell:

head -c 500 /dev/urandom | tr -dc a-z0-9A-Z | head -c 16; echo

A function to make a random password. cat gets some random stuff, tr makes it readable, and head defaults to 12 chars if nothing else if function is not called with a number:

function _rpass() {
        cat /dev/urandom | tr -cd '[:graph:]' | head -c ${1:-12}
}

_rpass 6
Personal tools
menu