Saturday, October 3, 2009

Exclamation mark in shell script and linux

The exclamation mark (!) in shell script just reverse the effect of test and exit status.
Example of ! about how it inverts the exit status of a command

$ cat >exit_status_check.sh
ls nofile_exist.txt
echo $?
! ls nofile_exist.txt
echo $?

$ sh exit_status_check.sh
ls: cannot access nofile_exist.txt: No such file or directory
2
ls: cannot access nofile_exist.txt: No such file or directory
0

In the example exclamation mark just reverse the exit status of ls command.

- With test operator "!" inverts the meaning of the test.

- ! is a bash keyword. With #, ! is used to determine the interpreter of shell command which is discussed on http://arjudba.blogspot.com/2009/04/what-is-sharp-bang-appear-at-first.html.

- ! also can be used as indirect variable assignment.
Example:

$ cat >indirect_ref.txt
v=variable
variable=2
echo "v = $v" # Direct reference.

echo "Now v = ${!v}" # Indirect reference.
# The ${!variable} notation is more intuitive than the old
#+ eval var1=\$$var2

$ sh indirect_ref.txt
v = variable
Now v = 2


- From the command line, the ! invokes the Bash history mechanism. Note that within a script, the history mechanism is disabled.

Related Documents

No comments:

Post a Comment