linux - Shell 脚本中的文件写入缓冲

标签 linux shell

我有一个启动 shell 脚本,它从文件中读取一个值,将其递增 1,然后将其写回。之后我对系统进行电源循环(关闭并打开电源)。我正在尝试使用这种方式记录重启次数。但我发现文件计数器始终保持为 1。如果我使用 reboot 命令重新启动,文件中的计数器会正确递增。这是因为文件写入被内核缓冲和延迟了。有没有办法强制它立即写入?

rc.user文件如下:

cd /root
bash bootcounter.sh
sleep 1

bootcounter.sh如下

rebootcount=$(<bootcount)
rebootcount=$(($rebootcount+1))
echo $rebootcount >bootcount

谢谢...

最佳答案

您需要同步命令。这应该刷新所有文件系统。

count=$( cat bootcount )
echo $( expr $count + 1 ) > bootcount
sync

不过,您可能应该使用 bootcount 的完整路径。

关于linux - Shell 脚本中的文件写入缓冲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5368803/

相关文章:

linux - 如何修复密码过期脚本中的无效日期错误

linux - 在 CC/GCC 构建期间, 'make' 是否未输出 "redirecting incorrect #include"警告?

python - 执行任务并在任务完成后关闭的 Shell 脚本

c++ - 使用 ioctl 在 C++ 中以编程方式添加路由

shell - 在 dockerfile 中插入条件 RUN 语句

c - 执行 ("/bin/sh", 0, 0);在管道中

shell - 如何从 fish shell 中的命令替换输出中捕获换行符?

linux - 使用 shell 脚本遍历 $PATH 变量

python - 这是什么错误? linux 下的 python 脚本

c - Linux C : What does the "S_Ixxxx" permission flag's "S" and "I" actually mean?