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
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
28 Feb, 2022
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...