2

I am running a script like this:

while IFS=$'\r' read -r line || [[ -n "$line" ]]; do
    something
done < "$1"

Basically, it reads a text file (as $1) and "do something" for each line.

The text file has 20 lines. If I modify the text file now by adding a line (line 21) when the script is running and working on line 10, will it work on line 21 later?

In other words, how the script read the text file? Read the whole file at once at beginning, or each line one by one when necessary?

1

Seems it's reading 1 line at a time, instead of reading whole file into memory at once. I've run a little test for you:

Create a file containing 3 lines:

$ echo -e "Line 1\nLine 2\nLine 3" >> teslines.txt
$ cat testlines.txt
Line 1
Line 2
Line 3

Create this little script:

#!/bin/bash

while read LINE; do
    echo "$LINE"
    sleep 2
done < testlines.txt

Run the script and start adding new lines:

$ ./readlinetest.sh
Line 1

# Somewhere around here i started adding more lines to the file:
$ echo "Line 4" >> testlines.txt
$ echo "Line 5" >> testlines.txt
$ echo "Line 6" >> testlines.txt
$ echo "Line 7" >> testlines.txt

# Output continued:
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7

It works pretty much like tail -f ran on some live log.

  • Thank you very much. I am wondering, in csh how I can do the similar thing. I mean, read each line at a time. The code I am using under csh seems read the whole file at once: foreach line (cat xxx.txt) (do things) end – michael morgan Mar 15 '18 at 1:32
  • @michaelmorgan I don't know csh (yet?), but I think it's a good idea to ask it as a separate question. Maybe even post it with expected behavior/code sample from bashas a reference. I know in perl this can be achieved using while and diamond <> operator. – yahol Mar 15 '18 at 8:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.