自行覆盖文件的最佳方法 [英] Best way to overwrite file with itself

查看:105
本文介绍了自行覆盖文件的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

读取文件然后将内容写入同一文件的最快/最优雅的方法是什么?

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

在Linux上,这并不总是与触摸"文件相同,例如如果文件代表某种硬件设备.

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

对我有用的一种可能性是echo $(cat $file) > $file,但我想知道这是否是最佳实践.

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

这篇关于自行覆盖文件的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆