如何在 shell 脚本中等待文件写入完成?

jcm*_*jcm 5 bash shell

我有一个名为 的 shell 脚本parent.sh,它执行一些操作,然后调用另一个 shell 脚本child.sh,该脚本执行一些处理并将一些输出写入文件output.txt

我希望parent.sh脚本仅在写入该文件后继续处理。output.txt我如何知道文件已完成写入?

编辑:添加问题的答案: child.sh 在退出之前是否完成了对文件的写入?是的

parent.sh是在前台运行child.sh还是在后台运行? 我不确定 - 它是从 withing 中调用的,parent.sh如下所示:./child.sh "$param1" "$param2"

shr*_*use 4

你需要wait命令。 wait将等到所有子流程完成后再继续。

父.sh:

#!/bin/bash

rm output.txt

./child.sh &

# Wait for the child script to finish
#
wait

echo "output.txt:"
cat output.txt
Run Code Online (Sandbox Code Playgroud)

孩子.sh:

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

这是以下的输出./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
Run Code Online (Sandbox Code Playgroud)