The general format for redirecting output on Bash/ksh shell is:
command > output.txt
command > /dev/device
However, you may end up overwriting file accidentally using > operator. For example:
$ ls -l *.c > output.txt
If file output.txt exists and is a regular file it will be overwritten. Say as a root user you typed "command > /etc/passwd" instead of "command < /etc/passwd". This can spell disaster for /etc/passwd file. On one occasion I had used > when I meant to use >> (append) operator.
How do I avoid accidental overwriting of a file on bash shell?
You can tell bash shell not to delete file data / contents by mistake by setting noclobber variable. It can keep you from accidentally destroying your existing files by redirecting input over an already-existing file.
How do I set noclobber option to prevent overwriting files on bash shell?
Open the Terminal and type the following command:
$ set -o noclobber
Create a test file:
$ echo "foo bar"> output.txt
Next, try to write to a file called output.txt:
$ cat > output.txt
ls -l > output.txt
bash: output.txt: cannot overwrite existing file
Add set -o noclobber to your ~/.bashrc file:
$ echo 'set -o noclobber' >> ~/.bashrc
How do I turn off noclobber on bash shell?
Type the following command:
$ set +o noclobber
Using + rather than - causes these flags to be turned off.
How do I temporary turn off noclobber on bash shell?
Sometime you just need to turn off noclobber for single operation. Use >| operator to force the file to be overwritten:
$ ls /etc >| output.txt
$ less output.txt
Putting it all together
Here is a quick demo about avoiding unintentional clobbering (overwrting) a file on bash and ksh shell:
- Chapter 6: Shell Redirection from Linux shell scripting wiki.
- Also, read bash man page for more information:
$ man bash
$ help set
- 30 Cool Open Source Software I Discovered in 2013
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012
- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop