Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to overwrite file with itself

Tags:

linux

bash

shell

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.

like image 640
fweth Avatar asked May 08 '14 17:05

fweth


2 Answers

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.

like image 159
Grzegorz Avatar answered Sep 22 '22 23:09

Grzegorz


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
like image 20
John Kugelman Avatar answered Sep 22 '22 23:09

John Kugelman