visc
visc

Reputation: 4959

Reading a file line by line from variable

I'm working on a script and it isn't clear how read -r line knows which variable to get the data from.. I want to read line by line from the FILE variable.

Here is the script I'm working on:

#!/bin/bash
cd "/"
FILE="$(< /home/FileSystemCorruptionTest/*.chk)" 

while read -r line
do
    echo "$line" > /home/FileSystemCorruptionTest/`date +%Y_%m_%d_%H_%M_%S`_1.log
done

echo "" > /home/FileSystemCorruptionTest/Done

Upvotes: 0

Views: 49

Answers (2)

kamikaze
kamikaze

Reputation: 1579

What you are requesting:

echo "${FILE}" | while read -r line …

But I think Tom's solution is better.

Upvotes: 1

Tom Fenech
Tom Fenech

Reputation: 74615

Since it looks like you want to combine multiple files, I guess that I would regard this as a legitimate usage of cat:

cat /home/FileSystemCorruptionTest/*.chk | while read -r line
do
    echo "$line"
done > /home/FileSystemCorruptionTest/`date +%Y_%m_%d_%H_%M_%S`_1.log

Note that I moved the redirect out of the loop, to prevent overwriting the file once per line.

Also note that your example could easily be written as:

cat /home/FileSystemCorruptionTest/*.chk > /home/FileSystemCorruptionTest/`date +%Y_%m_%d_%H_%M_%S`_1.log

If you only actually have one file (and want to store it inside a variable), then you can use <<< after the loop:

while read -r line
do
    echo "$line"
done <<<"$FILE" > /home/FileSystemCorruptionTest/`date +%Y_%m_%d_%H_%M_%S`_1.log

<<< "$FILE" has the same effect as using echo "$FILE" | before the loop but it doesn't create any subshells.

Upvotes: 2

Related Questions