Avoiding overwrites

You may have noticed in the output from the preceding commands that Bash does not prompt you about the destination file for an output redirection that doesn't exists  it creates it for you, without notifying you. Perhaps a bit more surprisingly, it won't prompt you if it replaces the contents of a file, either:

$ printf 'First command
' > myfile
$ printf 'Second command
' > myfile
$ cat myfile
Second command

The output from the first printf command is replaced with the output from the second printf command. If you don't want this to happen, and you only want to allow Bash to create new files, you can set the -C shell option with set:

$ set -C

For the running shell session, Bash will refuse to overwrite a file with a redirection operator:

$ printf 'Third command
' > myfile
bash: myfile: cannot overwrite existing file

However, you can force it to write anyway with the >| syntax:

$ set -C
$ printf 'Third command
' >| myfile
$

Don't forget that this only applies for your running shell. It doesn't prevent other running Bash shells or any other program from writing files. If you're writing a Bash script and you want to use the option, you need to include the set -C line near the top.

You may sometimes see the -C option referred to as noclobber. This is another Bash-specific name for the same option. We recommend -C, as it works in other shells, and is specified by POSIX.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.170.14