jcm
jcm

Reputation: 5659

How can I wait for a file to be finished being written to in shell script?

I have a shell script called parent.sh which does some stuff, then goes off and calls another shell script child.sh which does some processing and writes some output to a file output.txt.

I would like the parent.sh script to only continue processing after that output.txt file has been written to. How can I know that the file has finished being written to?

Edit: Adding answers to questions: Does child.sh finish writing to the file before it exits? Yes

Does parent.sh run child.sh in the foreground or the background? I'm not sure - it's being called from withing parent.sh like this: ./child.sh "$param1" "$param2"

Upvotes: 5

Views: 4047

Answers (1)

shrewmouse
shrewmouse

Reputation: 6020

You need the wait command. wait will wait until all sub-processes have finished before continuing.

parent.sh:

#!/bin/bash

rm output.txt

./child.sh &

# Wait for the child script to finish
#
wait

echo "output.txt:"
cat output.txt

child.sh:

#!/bin/bash
for x in $(seq 10); do
    echo $x >&2
    echo $x
    sleep 1
done > output.txt

Here is the output from ./parent.sh:

[sri@localhost ~]$ ./parent.sh 
1
2
3
4
5
6
7
8
9
10
output.txt:
1
2
3
4
5
6
7
8
9
10

Upvotes: 4

Related Questions