Paebbels
Paebbels

Reputation: 16221

Open file descriptor in Bash in overwrite mode

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:

Upvotes: 1

Views: 312

Answers (2)

ingroxd
ingroxd

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:

  • 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.

Upvotes: 1

root
root

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

Related Questions