Timestamp your bash history – Modify .bashrc

Need a date and/or time stamp in your bash history? Simply set the HISTTIMEFORMAT in your (or other users) .bashrc file:


Now the ‘history’ command shows your timestamp next to the command issued:

[root@hostname ~]# history | tail -n4
998 05/21/12 11:25:41 vi .bashrc
999 05/21/12 11:25:41 exit
1000 05/21/12 11:25:43 ls
1001 05/21/12 11:25:46 history | tail -n5

history timestamp - techpain.com


Bash Scripting repetitive tasks – while read x; do

Use a “while loop” type bash script for repetitive Linux tasks

More “while loop” bash scripting examples at tldp.org

An audit on a Linux server made it necessary to get information regarding every user on the machine, and match those users to a mail directory (which may or may not have a different name). Instead of running the ‘finger’ command three hundred times and copying the output somewhere I used this:
#! /bin/sh
while read username; do
finger ${username}
done < inputfile > outputfile
exit 0

I saved this as finger_script.sh and copied each of the usernames to the file ‘inputfile’. The ‘inputfile’ contained just the usernames that I cut and pasted from the mail directory in question, and looked like this:
bill frank keith user01 user05 user09
carl gary larry user02 user06 user10
dan heather mary user03 user07 user11
denise joe nancy user04 user08 user12

Running finger_script.sh ran the finger command on each user in the ‘inputfile’ and immediately output a list of users that did not exist. It also created ‘outputfile’, which contained a list of the information on each user:
Login: bill Name: Bill Person
Directory: /home/b/bill Shell: /bin/nologon
Never logged in.
No mail.
No Plan.
Login: carl Name: Carl Guy
Directory: /users/carl Shell: /bin/nologon
Never logged in.
No mail.
No Plan.
Login: dan Name: Dan Theman
Directory: /users/dan Shell: /bin/nologon
Never logged in.
No mail.
No Plan.


Show or Delete Files Older than x Days – Bash

Bash Script with a Variable for removing old files


Here are some commands that you can use in bash scripts for file cleanups:

Show files and directories more than 15 days old:
find /path/to/files/* -mtime +15

Delete files more than 15 days old:
find /path/to/files/* -mtime +15 -exec rm {} ;

These can, of course, be scripted (and cron’d, if you set the -mtime flag instead of using a variable). A script to show the files and directories older than x days would look like:
#!/bin/bash --
find /path/to/files/* -mtime $1

And to delete those same files:
#!/bin/bash --
find /path/to/files/* -mtime $1 -exec rm {} ;

Just remember to set the permissions of the script to allow execution, and pass the variable on the command line like so:
# MyScriptName +15

howtogeek.com has a detailed explanation of the command.


Create MySql DB and Grant Permissions – Shell Script

Another script from nixCraft. This one is for creating and setting permissions on a MySql database.

# A shell script to add mysql database, username and password.
# It can also grant remote access on fly while creating the database.
# -------------------------------------------------------------------------
# Copyright (c) 2007 nixCraft project
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# -------------------------------------------------------------------------
# Last updated on Jan/09/2010
# -------------------------------------------------------------------------

## Path to mysql bins ##
## Mysql root settings ##

# make sure we get at least 3 args, else die
[[ $# -le 2 ]] && { echo "Usage: $0 'DB_Name' 'DB_USER' 'DB_PASSORD' ['remote1|remote2|remoteN'] ['DB_RIGHTS']"; exit 1; }

# fallback to ALL rights
[[ -z "${_dbrights}" ]] && _dbrights="ALL"

# build mysql queries
_uamq="${mysql} -u "${_madminuser}" -h "${_mhost}" -p'${_madminpwd}' -e 'CREATE DATABASE ${_db};'"
_upermq1="${mysql} -u "${_madminuser}" -h "${_mhost}" -p'${_madminpwd}' -e "GRANT ${_dbrights} ON ${_db}.* TO ${_user}@localhost IDENTIFIED BY '${_pass}';""

# run mysql queries

# read remote host ip in a bash loop
# build queires to grant permission to all remote webserver or hosts via ip using the same username
for i in ${_dbremotehost}
_upermq2="${mysql} -u "${_madminuser}" -h "${_mhost}" -p'${_madminpwd}' -e "GRANT ${_dbrights} ON ${_db}.* TO ${_user}@${i} IDENTIFIED BY '${_pass}';""

To use the script:

./script.sh dbname username password


/script.sh dbname username password '|'
(to allow and


/script.sh dbname username password '|' 'SELECT,INSERT,UPDATE,DELETE'
(to allow and and only grant SELECT,INSERT,UPDATE,DELETE)


Linux Disk Space Alerts – Cron’d Shell Script

The following steps are for setting up an email notification to alert you of low disk space on *nix boxes.

1) Write a script. I modified a script that I found at nixCraft that checks disk space and sends an email if the used space is above a specified percentage. I made some adjustments to that script, here is what I am using:

# Shell script to monitor or watch the disk space
# It will send an email to $ADMIN, if the used percentage
# of space is >= 90%
# -------------------------------------------------------------------------
# Copyright (c) 2005 nixCraft project
# This script is licensed under GNU GPL version 2.0 or above
# -------------------------------------------------------------------------
# This script is part of nixCraft shell script collection (NSSC)
# Visit http://bash.cyberciti.biz/ for more information.
# ----------------------------------------------------------------------
# Linux shell script to watch disk space (should work on other UNIX oses )
# SEE URL: http://www.cyberciti.biz/tips/shell-script-to-watch-the-disk-space.html
# set admin email so that you can get email
# set alert level 90% is default
df -HP | grep -vE '^Filesystem|tmpfs|cdrom' |
  while read partition size used free perc mnt ;
    usep=$(echo $perc | tr -d '%' )
    if [ $usep -ge $ALERT ]; then
      echo "Running out of space "$partition ($usep%)" on $(hostname) as
  on $(date)" |
       mail -s "Alert: Almost out of disk space - $usep%" $ADMIN

2) Create a cron job. I simply copied the script into /etc/cron.hourly and set the permissions (chmod +x /etc/cron.hourly/diskalertscript). Alternatively, you can add it to crontab to further customize when it runs:
crontab -e
10 0 * * * /path/to/diskalertscript


Bash Script – Quick Reference

This the basic Bash Script quick reference useful to those, who do not often write bash scripts, and need an intermitent refresher on how basic things are done. This is not a comprehensive reference, nor will it be of use to any one who is more experienced with Bash shell.

Bash expressions contain variables and operators such as == (equals) and > (greater
than). These operators are usually used in tests, which can be specified in several ways:
test $file == "test"
[ $file == "test" ]
[[ $file == "test" ]]

If you use the test command, remember that some symbols have multiple meanings
(for instance, in an earlier section we used > for output redirection), so they need to
be enclosed in quotes. You don’t have to worry about the quotes if you use the single
or double square bracket syntax. The double brackets do everything the single
ones do and a bit more, so it’s safest to use double brackets with your expressions.

bash has some useful special built-in operators:
-a file # true if file exists
-d file # true if file exists and is a directory
-f file # true if file exists and is a file
-r file # true if file exists and is readable
-w file # true if file exists and is writable
-x file # true if file exists and is executable

bash is heavily weighted toward text such as commands, arguments, and filenames.
It can evaluate the usual arithmetic expressions (using +, -, *, /, and other operators)
by surrounding them with a pair of double parentheses: ((expression)). Because
many arithmetic characters–including *, (, and )–are specially interpreted by the
shell, it’s best to quote shell arguments if they will be treated as math expressions in
the script:

Simple calculator (./calc)
result=$(( $* ))
echo $result

$ ./calc "(10+1)*(9-1)-40"

$ ./calc "2*100"

The latest version of bash supports 64-bit integers, while older versions only supported 32-bit. Floating-point numbers are not supported. Scripts that need floating-point or more advanced operators can use an external program
such as bc.

The if … fi
Given expressions, you can execute different chunks of code depending on the
results of tests. bash uses the if … fi (backwards if) syntax, with optional elif
(else if) and else sections:
if expression1 ; then
elif expression2 ; then

elif expressionN ; then
else (commands)

The ; then phrase at the end of a line can also be expressed as a plain then on the
next line:
if expression

Taken from goitexpert.com