My answer here, resulted in this comment:
This could be subject to a TOCTOU1 attack and needs to be developed to be correct.
The answer is in Rust, but here's some equivalent bash:
p=/home/roger/foo/bar/baz.txt
d=$(dirname $p)
mkdir -p $d
# ...and then (implied):
echo "Hello World" > $p
Where is the TOCTOU vulnerability in this? How can it be improved?
1 Time Of Check - Time Of Use