Shell options

When we are using bash shell in Linux, we can see the current options by using the command:

set -o

if we want to enable options:

set -o <option>

if we want to disable option back then:
set +o <option>

A very useful shell option is the noclobber option. It prevent the overwriting of an existing file when using redirect with “>” redirect sign.
So if we set this option and we try to redirect output or standard error of command into existing file by using “> existingFileName“(instead of appending i.e. “>>“)   then it will throw an error and prevent it.
For example:


[oren@localhost ~]$ ls > data
[oren@localhost ~]$ ls > data
[oren@localhost ~]$ set -o noclobber 
[oren@localhost ~]$ ls > data
-bash: data: cannot overwrite existing file
[oren@localhost ~]$ ls > data1
[oren@localhost ~]$ ls > data1
-bash: data1: cannot overwrite existing file
[oren@localhost ~]$ ls > data2

AS we can see before we set the noclobber, we could overwriting the file data.We know that we overwriting this file because we redirect to it twice.However once we set the noclobber (with the “set -o noclobber” command) and tried to redirect again to same file it failed and we got the following message “-bash: data: cannot overwrite existing file“. We can still redirect the standard output to a new file (data1).But if we try to redirect again to this file (existing file), the we fail again and file content is saved (from being changed).
So this option is pretty useful and can prevent the overwriting of a file.
If we have this option on, and we still want to overwriting the file then we can use “>|“, and in such case it will overwriting existing file with the standard output.
For example (lets continue with previous code):


[oren@localhost ~]$ ls > data
[oren@localhost ~]$ ls > data
[oren@localhost ~]$ set -o noclobber 
[oren@localhost ~]$ ls > data
-bash: data: cannot overwrite existing file
[oren@localhost ~]$ ls > data1
[oren@localhost ~]$ ls > data1
-bash: data1: cannot overwrite existing file
[oren@localhost ~]$ ls > data2
[oren@localhost ~]$ ls > data2
-bash: data2: cannot overwrite existing file

[oren@localhost ~]$ ls >| data2
[oren@localhost ~]$ ls >| data1
[oren@localhost ~]$ ls >| data
[oren@localhost ~]$ 

As we can see once we use “>|” then it overwriting the file despite the noclobber option on, and it doesn’t throw error that it can not overwrite the file.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s