Contents

Linux中Shell文件保护

1. 概述

除了保护我们的文件不被滥用的 Linux 文件权限外,大多数 Linux shell 都有一个内置的保护机制来防止意外的文件覆盖。在本文中,我们将讨论这些保护措施的用法。

2. 使用noclobber保护文件

大多数 POSIX shell(如果不是全部)都实现了noclobber选项。这意味着如果 shell 重定向试图覆盖现有文件,shell 会抱怨。

默认情况下,主要由于传统,noclobber选项被禁用。要在bash 或 ksh 中打开它,我们将使用以下命令:

set -o noclobber

使用cshtcsh 时,我们将选项设置如下:

set noclobber

一旦我们设置了noclobber选项,如果我们试图覆盖一个文件,bash会报错:

set -o noclobber
touch temp.txt           # Create temp.txt file
echo "Hello" > temp.txt  # Try to overwrite file contents
-bash: temp.txt: cannot overwrite existing file

使用csh / tcsh,错误信息有点神秘:

set noclobber
touch temp.txt           # Create temp.txt file
echo "Hello" > temp.txt  # Try to overwrite file contents
temp.txt: File exists

我们应该注意,这只会保护我们免受使用重定向的文件覆盖。通过rm 删除文件,通过“ » ”重定向附加到文件,或者只是从进程中写入文件将继续正常工作。

3. 压倒一切的保护

要覆盖noclobber保护,我们可以通过禁用 shell 选项或暂时覆盖它们来返回默认行为。要禁用bashksh中的noclobber限制,我们使用bash选项语义:

set +o noclobber

tcsh / *csh 中,*这转换为:

unset noclobber

为了临时覆盖noclobber行为,我们的 shell 进程提供了特殊的重定向操作符:“ >! ” 和 “ >| “ 分别。让我们使用bash展示我们的原始示例:

set -o noclobber
touch temp.txt           # Create temp.txt file
echo "Hello" > temp.txt  # Try to overwrite file contents
-bash: temp.txt: cannot overwrite existing file
echo "Hello" >| temp.txt  # Overwrite file contents using override operator

使用tcsh时,我们只需替换“>|” 用“>!”:

set noclobber
touch temp.txt           # Create temp.txt file
echo "Hello" > temp.txt  # Try to overwrite file contents
temp.txt: File exists
echo "Hello" >! temp.txt  # Overwrite file contents using override operator

4. 示例:截断日志文件

我们可能需要此功能的一个经典示例是截断日志文件时。因此,日志文件往往由记录数据的服务保持打开状态。因此,我们通常无法删除它们,因为操作系统会在打开的文件句柄上保留一个选项卡。为了截断日志文件,我们将*/dev/null*重定向到该文件:

/dev/null >| my_logfile.log

**该解决方案具有额外的好处,即如果文件未更改,则不更新修改时间。**这意味着如果我们在 crontab 中运行重定向并且文件保持为空,则修改时间将反映文件上次被截断的时间。

在这种情况下可以不使用命令行重定向的另一个选项是truncate 。以下示例将具有与前一个相同的效果,有效地将文件大小调整为 0:

truncate -s 0 my_logfile.log

truncate命令还有一个额外的好处,因为它允许我们将文件调整为任意大小。以下示例将我们的日志文件大小调整为 50MB:

truncate -s 50M my_logfile.log