用文件描述符覆盖文件的内容

时间:2017-05-20 06:24:53

标签: shell sh posix

如何通过文件描述符完全覆盖文件内容?

已经有一个问题问同样的问题,但没有明确答案: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.

0 个答案:

没有答案