Reading from file by lines instead of words (columns)

This one was tricky. My colleague needed to process text file by lines instead of words. Lets say you have following text file:

word1 word2
word3 word4

If you use old “for i in `cat file`; do; echo $i; done” output will be like

word1
word2
word3
word4

But when you need to cut the file by lines, following code might come in handy:

while read i
do
echo "This is new line $i"
done < file

which will output

This is new line word1 word2
This is new line word3 word4

Unix if statement “Parameter not set.” error when test variable is empty

Let’s say you want to test if variable is empty or not:

if [ -n $TOP ]
then
command
fi

This is perfectly normal if the variable $TOP is not empty, but otherwise this test stops with an error “Parameter not set“. The solution is quite easy:

if [ -n "$TOP" ]
then
command
fi

You enclose the variable in “” so that test can be always done against something and doesn’t display silly errors.