0

I am doing something interesting with bash

I wrote script below:

#!/bin/bash
while :
do
    if [ -s /tmp/file.txt ]; then
        for line in $(cat /tmp/file.txt)
        do
            echo $line
            #May be some commands here
        done
    fi
done

and the content of my file.txt is:

1 True
2 Flase

How can I say the script if command cat /tmp/file.txt is finished (I mean all lines are read) and also echo $line and other commands are finished then break the infinitive while : loop?

Thank you

2
  • Why did you set the while loop ? you can remove it from this code it's useless.only if you want to test if the content of the file is ready, in this case you should use a sleep 10 to not overload your CPU Commented May 31, 2014 at 11:20
  • This is needed because of some commands are running in back ground. I want to say while the pids of that commands are alive infinite while works Commented May 31, 2014 at 11:22

1 Answer 1

2

Use break.

#!/bin/bash
while :
do
    if [ -s /tmp/file.txt ]; then
        for line in $(cat /tmp/file.txt)
        do
            echo $line
            #May be some commands here
        done
        break
    fi
done

Although it would be simpler and more proper with:

#!/bin/bash
for (( ;; )); do
    if [[ -s /tmp/file.txt ]]; then
        # Never use `for X in $()` when reading output/input. Using word splitting
        # method for it could be a bad idea in many ways. One is it's dependent with
        # IFS. Second is that glob patterns like '*' could be expanded and you'd
        # produce filenames instead.
        while read line; do
            # Place variables between quotes or else it would be subject to Word
            # Splitting and unexpected output format could be made.
            echo "$line"
        done < /tmp/file.txt
        break
    fi
done

On another note, do you really need the outer loop? This time you don't need to use break.

#!/bin/bash
if [[ -s /tmp/file.txt ]]; then
    while read line; do
        echo "$line"
    done < /tmp/file.txt
fi
Sign up to request clarification or add additional context in comments.

2 Comments

Yes I do, because I am running some commands in background. So I want to tell the commands in if [[ -s /tmp/file.txt ]]; then` to be ran while that commands in background are alive
If that's the case I'd suggest inserting a sleep command at the end of the loop to avoid letting your script hug all your processing power while it's not reading a file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.