Tuesday, April 22, 2008

Bash Tip of the Day! variable tricks

One very little known part of Bash is variable substitution and matching. Say you have a script where you want to use the value of a variable if it has a value, but use a default value if it is null, you can use the following example:

NEWVAL=${CURVAL:-default}


This will assign the value of ${CURVAL} to ${NEWVAL} if not null, otherwise it will assign the value of default to ${NEWVAL}. Note that this will not change the value of ${CURVAL} -- although that is possible with the following example:

NEWVAL=${CURVAL:=default}


Another great trick to use with Bash are the substitution operators. I am often trying to solve problems where I take a filename and I would like to remove a part of the name which is a consistent pattern and manipulate the filename to a new format. Logrotate often appends a dot and a number to filenames which is a great thing, but sometimes that is not desireable after the fact. You can easily change this:


export FILE=maillog.12
NEWNAME=${FILE%.*}


This might be more useful as a small script to rename rotated files to date-related files:


FILELIST=$(find /var/log/ -type f -name "*maillog*" -print)

for file in ${FILELIST}
do
BASE=${file%.*}
BASE=${BASE##*/}
DATE=$(date +%Y%m%d)
HOUR=$(tail -n 1 ${file} | awk '{print $3}' | awk -F: '{print $1$2}')
mv ${file} /new/location/${BASE}-${DATE}-${HOUR}.log
done


And with that you have an archive location with each file named to indicate the date and time of the log.

Friday, April 18, 2008

Bash Tip of the Day! for loops

Today's tip covers Bash for loops. A simple operation that comes in handy with nearly EVERY shell script.


for i in $(seq 1 10)
do
echo ${i}
done


Note that enclosing variables in curly braces is not required but will never let you down. Take the following code, for example:


i=1
echo $i # works
echo $i5 # won't work!
echo ${i}5 # works!


Enclosing the variable in curly braces allows you to use the variable anywhere, without fear of Bash interpreting surrounding characters as part of the variable.