Thursday 12 November 2009

bash shell options

I don't want to expand the special character "*" . I want to find a file exactly named "*.txt".I can do that by escaping but there is a good feature in bash that is its options to disable globbing as follows.


The following command executes a script in POSIX-compatible mode:

sriram:~$ bash --posix script.sh

For changing the current environment temporarily, or for use in a script, we would rather use set. Use - (dash) for enabling an option, + for disabling:


sriram:~$ set -o noclobber
sriram:~$ touch test
sriram:~$ date > test
bash: test: cannot overwrite existing file
sriram:~$ set +o noclobber
sriram:~$ date > test

The above example demonstrates the noclobber option, which prevents existing files from being overwritten by redirection operations. The same goes for one-character options, for instance -u, which will treat unset variables as an error when set, and exits a non-interactive shell upon encountering such errors:

sriram:~$ echo $VAR
sriram:~$ set -u
sriram:~$ echo $VAR
bash: VAR: unbound variable

This option is also useful for detecting incorrect content assignment to variables: the same error will also occur, for instance, when assigning a character string to a variable that was declared explicitly as one holding only integer values.


One last example follows, demonstrating the noglob option, which prevents special characters from being expanded:

sriram:~$ set -o noglob
sriram:~$ touch *
sriram:~$ ls -l *
-rw-rw-r-- 1 sriram sriram 0 Feb 27 13:37 *

No comments:

Post a Comment

Tweets by @sriramperumalla