문제

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.

도움이 되었습니까?

해결책

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

다른 팁

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.

The sponge utility in the moreutils package allows this

~$ cat file
foo
~$ cat file | sponge file
~$ cat file
foo
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top