Bash – Maintain (or restore) file permissions when replacing file

bashfilespermissionsscripting

I have a command that accepts a file as an argument, modifies the file, then writes it to the file name specified in the second argument. I'll call that program modifyfile.

I wanted it to work "in place" so I wrote a shell script (bash) that modifies it to a temporary file then moves it back:

TMP=`mktemp`
modifyfile "$original" "$TMP"
mv -v "$TMP" "$original"

This has the unfortunate side effect of destroying the permissions on this file. The file gets re-created with default permissions.

Is there a way to tell the mv command to overwrite the destination without altering its permissions? Or alternately is there a way to save the user, group, and permisssions from the original and restore them?

Best Answer

Instead of using mv, just redirect cat. For example:

TMP=$(mktemp)
modifyfile "$original" "$TMP"
cat "$TMP" > "$original"

This overwrites $original with the contents of $TMP, without touching anything at the file level.

Related Question