fweth
fweth

Reputation: 685

Best way to overwrite file with itself

What is the fastest / most elegant way to read out a file and then write the content to that same file?

On Linux, this is not always the same as 'touching' a file, e.g. if the file represents some hardware device.

One possibility that worked for me is echo $(cat $file) > $file but I wondered if this is best practice.

Upvotes: 11

Views: 11238

Answers (3)

Grzegorz
Grzegorz

Reputation: 3335

I understand that you are not interested in simple touch $file but rather a form of transformation of the file.

Since transformation of the file can cause its temporary corruption it is NOT good to make it in place while others may read it in the same moment.

Because of that temporary file is the best choice of yours, and only when you convert the file you should replace the file in a one step:

cat "$file" | process >"$file.$$"
mv "$file.$$" "$file"

This is the safest set of operations.

Of course I omitted operations like 'check if the file really exists' and so on, leaving it for you.

Upvotes: 7

Emilien
Emilien

Reputation: 2445

The sponge utility in the moreutils package allows this

~$ cat file
foo
~$ cat file | sponge file
~$ cat file
foo

Upvotes: 7

John Kugelman
John Kugelman

Reputation: 361685

You cannot generically do this in one step because writing to the file can interfere with reading from it. If you try this on a regular file, it's likely the > redirection will blank the file out before anything is even read.

Your safest bet is to split it into two steps. You can hide it behind a function call if you want.

rewrite() {
    local file=$1

    local contents=$(< "$file")
    cat <<< "$contents" > "$file"
}

...

rewrite /sys/misc/whatever

Upvotes: 11

Related Questions