1

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:

  • delete the file before opening with rm $Reproducer.
Paebbels
  • 15,573
  • 13
  • 70
  • 139

2 Answers2

1

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:

  • Your new script will not have any junk left at the end;
  • If the process fails before finish, you will not delete your previous script and you are still able to recover your partially created file.
ingroxd
  • 995
  • 1
  • 12
  • 28
0
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.

root
  • 5,528
  • 1
  • 7
  • 15