Leonardo
Leonardo

Reputation: 2363

Read a file using a bash script

I need to read a file using a "Do/While" loop.
How can I read the contents as a string?

Here's my code:

cat directory/scripts/tv2dbarray.txt | while read line
do
  echo "a line: $line"
done

Error:

test.sh: line 4: syntax error near unexpected token `done'
test.sh: line 4: `done'

Upvotes: 34

Views: 115736

Answers (4)

Adam Liss
Adam Liss

Reputation: 48330

There's no reason to use cat here -- it adds no functionality and spawns an unnecessary process.

while IFS= read -r line; do
  echo "a line: $line"
done < file

To read the content of a file into a variable, use foo=$(<file). (Note that this trims trailing newlines.)

Upvotes: 130

pedram shabani
pedram shabani

Reputation: 1680

try it

while read p
do 
echo $p
done <  directory/scripts/tv2dbarray.txt

Upvotes: 0

prudviraj
prudviraj

Reputation: 3744

This should work:

file=path/of/file/location/filename.txt

while IFS= read -r varname; do
    printf '%s\n' "$varname"
done < "$file"

Upvotes: 4

Erik
Erik

Reputation: 91320

cat file | while read line
do
  echo "a line: $line"
done

EDIT:

To get file contents into a var use:

foo="`cat file`"

Upvotes: 45

Related Questions