user6417385
user6417385

Reputation:

Bourne shell scripting reading file

This simple program supposed to read the file lines, but instead it outputs "cat" every time. What is the problem?

#!/bin/sh
while read line
do
  echo $line
done <file

Edit:

file is supposed to be the users input file when calling the program from the terminal. Like:

./programname file 

Upvotes: 2

Views: 2206

Answers (1)

sjsam
sjsam

Reputation: 21965

this is suppose to be the users input file when calling the program from the terminal. Like: ./programname file

In this case you should be doing

#!/bin/sh
if [ -f "$1" ] # checking if file exist
then 
 while read line
 do
   echo "$line"
 done <"$1" # double quotes important to prevent word splitting
else
  echo "Sorry file $1 doesn't exist"
fi

Here $1 represents the first parameter that you pass to the script.

Interesting reads:

  1. What is [ word splitting ] ?
  2. Shell script [ parameters ]

Upvotes: 3

Related Questions