Wednesday, June 01, 2005

Bash - Using Input Field Separators

Consider the following snippet:
#!/bin/bash

for i in `/bin/cat /etc/passwd`
do
if echo $i grep $1 # To see how this works, check
here
then
echo "Found $1"
exit 0
fi
done
echo "Not found $1"
exit 1


This might not work in all cases. Consider this user:
ftp:*:14:50:Only ftp user:/var/ftp:/sbin/nologin

When we search for the user ftp, the output is:
$ sh cond.sh ftp
ftp:*:14:50:Only
Found ftp


This is not the expected output. To get over this issue, we can use the shell variable IFS to set the field separator for the input provided as some other character.

The solution would be:
#!/bin/bash

IFS="^M" # To see how this must be done, check here
for i in `/bin/cat /etc/passwd`
do
if echo $i grep $1 # To see how this works, check
here
then
echo "Found $1"
exit 0
fi
done
echo "Not found $1"
exit 1

The output would now be:
$ sh cond.sh
ftp ftp:*:14:50:Only ftp user:/var/ftp:/sbin/nologin
Found ftp

Hope this helps,

Rgds,
Karthick S.

0 comments: