views:

173

answers:

4

What is the meaning for $! in shell or shell scripting? I am trying to understand a script which has the something like the following.

local@usr> a=1
local@usr> echo $a
1
local@usr> echo $!a
a

It is printing the variable back. Is it all for that? What are the other $x options we have? Few I know are $$, $*, $?. If anyone can point me to a good source, it will be helpful. BTW, This is in Sun OS 5.8, KSH.

+2  A: 

From the ksh man page on my system:

  ${!vname}
      Expands  to the name of the variable referred to by vname.  This
      will be vname except when vname is a name reference.
Greg Hewgill
+1. Thanks. What are the other options available?
Guru
An example perhaps? Expands confuses me. :(
Guru
`man ksh` will tell you, there are too many to copy into an answer here.
Greg Hewgill
This form is referred to as indirection. `a=1; b=a; echo ${!b}` results in "1" being printed.
Dennis Williamson
+3  A: 

The various $… variables are described in Bash manual. According to the manual $! expands to the PID of the last process launched in background. See:

$ echo "Foo"
Foo
$ echo $!

$ true&
[1] 67064
$ echo $!
67064
[1]+  Done                    true

In ksh it seems to do the same.

zoul
+1. Nice. I would like to see an example please.
Guru
What does that mean? I tried and I could not understand what is it?usr> echo $!17893usr> falseusr> echo $!17893
Guru
Guru, try this: sleep 120 echo $1 ; ps -ef | grep $!
paxdiablo
It's the PID of the last *background job - it won't change until you run a background job.
paxdiablo
@paxdiablo. Great. Now, I am understanding.
Guru
A: 

It gives the Process id of last backgroundjob or background function Please go through this link below

http://www.well.ox.ac.uk/~johnb/comp/unix/ksh.html#specvar
Sachin Chourasiya
+1  A: 

! is a reference operator in unix, though it is not called with that name.

It always refers to a mother process. Try typing :! in vi, it takes you to command prompt and you can execute commands as usual until exit command.

! in SQLPLUS also executes the command from the command prompt. try this in sqlplus

SQL> !ls --- this gives the list of files inthe current dir.

$! - obviously gives the process id of the current/latest process.

Venkataramesh Kommoju
+1. Good explanation. Thanks for the comparision.
Guru