Reputation: 16221
I'm opening additional file descriptors in my Bash script with
Reproducer="reproducer.sh"
exec 3<> $Reproducer
This can then be used with e.g. echo
echo "#! /bin/bash" >&3
echo "echo This is a reproducer script." >&3
Source: How do file descriptors work?
As I noticed after lots of tries, the opened file overwrites existing content in the file. If the new content is larger, it will expand the file, but if the new content has less bytes, the old content will remain at the end of the file.
This creates a broken script in my case, because I'm writing a Bash script.
Is there an option to the exec 3<> file
statement to truncate the file while opening?
Alternative solutions:
rm $Reproducer
.Upvotes: 1
Views: 312
Reputation: 1025
One of the things you can do is to create a temp file and replace the old with this one.
exec 3<>/tmp/script
printf "%s\n" "#!/bin/bash" >&3
printf "%s\n" "printf \"This is a reproducer script.\n\"" >&3
exec 3>&-
mv /tmp/script "${Reproducer}"
You will achieve two things:
Upvotes: 1
Reputation: 6048
exec 3>$Reproducer
Should work unless you need to read the file. in that case:
exec 3>$Reproducer 4<$Reproducer
and you read from file descriptor 4.
Upvotes: 0