Open In App
Related Articles

How to protect Linux shell file using noclobber in bash shell?

Improve Article
Improve
Save Article
Save
Like Article
Like

Most Linux shells(bash, csh, ksh, tcsh) have a built-in file protection mechanism to prevent files from being overwritten accidentally. In this article, we will see how to prevent it by setting noclobber option.

Clobbering

Redirecting standard output to a file that already exists would overwrite the existing file content which will result in data loss. This process of over-writing existing data is called clobbering. In order to prevent overwriting, the shell provides an option called “noclobber”

File protection using noclobber:

When noclobber option is set, then the shell will complain if a shell redirect(>) is trying to overwrite an existing file. noclobber option is activated using the set command in bash/ksh. By default, the option is disabled.

Setting noclobber

Once the option is enabled, bash will complain if we try to overwrite a file,

File over-write error

Overriding protections:

To override noclobber behavior temporarily a special redirection operator (>|) is used,

Disable noclobber using >|

Another way is to return to the default behaviour by disabling the shell option,

Disable noclobber in shell

By default, noclobber option is disabled, and to enable it whenever a new shell is spawned it needs to be added in the startup script (~/.bashrc),

Add noclobber in bashrc

noclobber option protect file overwrites only for redirection. Removing the file through rm and appending it to the file via “>>” redirection works normally.

noclobber only for >

Truncating a log file:

Log files are kept open by the service logging the data. It is not possible to delete them as the operating system is keeping a tab on the open file handles. To truncate the log file, we redirect /dev/null to the file using the override operator.

/dev/null >| my_logfile.log
Last Updated : 28 Feb, 2022
Like Article
Save Article
Similar Reads