Protecting files with noclobber

To protect files on Linux by accidently overwritten by > operator, you can use

set -o noclobber

Now if you try to overwrite a file with >, you will get error

root@ok:~# echo "Hello" > 1.txt
-bash: 1.txt: cannot overwrite existing file
root@ok:~# 

If you really need to overwrite, use >! operator.

echo "Hello" >! FILE_NAME

Example

root@ok:~# echo "Hello" > 1.txt
-bash: 1.txt: cannot overwrite existing file
root@ok:~# echo "Hello" >! 1.txt
root@ok:~# 

Instead of running the command “set -o noclobber” everytime, you can add it to .bashrc file.

Need help with Linux Server or WordPress? We can help!

Leave a Reply

Your email address will not be published. Required fields are marked *