Shell script to read a file line by line

This is a simple shell script to read a file line by line

while read line
do
  echo $line
done < libraries-php.txt

Now execute the program

$ source read.sh
php5-cgi - server-side, HTML-embedded scripting language (CGI binary)
php5-cli - command-line interpreter for the php5 scripting language
php5-common - Common files for packages built from the php5 source

The above program can be modified to take file name as as an argument and some additional checks

#! /bin/sh
if [ $# -ne 1 ]
then echo "Usage: read.sh filename";
exit 1;
fi

if [ ! -f $1 ]
then echo "File $1 doesn't exist";
exit 1;
fi

while read line
do
  echo $line
done < $1

Now the program can take file name as argument

$ source read.sh libraries-php.txt
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s