fweth fweth - 1 month ago 17
Bash Question

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.

Answer

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