如何通过文件描述符完全覆盖文件内容?
已经有一个问题问同样的问题,但没有明确答案:Bash, overwrite using file descriptor?。
script.sh:
#!/bin/sh -e -x
echo "Hello world, this is a test." >&3
sleep 1
cat ./state
sleep 1
echo "Hello." >&3
sleep 1
cat ./state
parent.sh:
#!/bin/sh -e -x
echo "" > ./state
exec 3> ./state
./script.sh
运行parent.sh
,预期输出:
+ echo ''
+ exec
+ ./script.sh
+ echo 'Hello world, this is a test.'
+ sleep 1
+ cat ./state
Hello world, this is a test.
+ sleep 1
+ echo Hello.
+ sleep 1
+ cat ./state
Hello.
实际输出:
+ echo ''
+ exec
+ ./script.sh
+ echo 'Hello world, this is a test.'
+ sleep 1
+ cat ./state
Hello world, this is a test.
+ sleep 1
+ echo Hello.
+ sleep 1
+ cat ./state
Hello world, this is a test.
Hello.