0

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 
4
  • is this a toy example? why do you read the file into a variable? Commented Mar 24, 2016 at 12:52
  • I'm reading the contents of a file into a variable because I'll have many while loops proceeding one another Commented Mar 24, 2016 at 12:55
  • That doesn't really explain why you don't simply cat the file to the log file. What do you actually want to accomplish? Using a shell loop to process a file line by line is often something you want to avoid. Commented Mar 24, 2016 at 13:10
  • 1
    This is covered by Bash FAQ 001. Commented Mar 24, 2016 at 13:18

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

What you are requesting:

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

But I think Tom's solution is better.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.