What does kill $! do?

What does $! return?

Killing background processes

root@:~# sleep 100 &
[1] 13829
root@:~# echo $!
13829
root@:~# kill $!
root@:~# 

Thanks...
Does it kill all the background process or the latest?

only the latest. but why didnt you try yourself ?. If you want to come along with unix you need to be keen to experiment. relying on the forum may be comfortable, but dosnt bring you any further.

Thanks,

But i have a query here
Please view this code:-

#!/usr/bin/ksh
read a &
sleep 5
kill $!

Now in these 5 secs if there is another background process invoked in the system will that process be killed?

no $! is only set within the current shell processes running in different shells are not affected. there might be a problem with your script when you sleep to long and murphy is on the way. for ex. when you sleep 3600 and read finishes after a few seconds another process may have been executed on the system using the same pid. if you want to be precize you have to test if $! points to your read process.

  • is the process $PID a child of this shell ?
    you can determine the PID of your shell with echo $$

to make it easy

read ....
for i in 1 2 3 4 ; do 
 sleep $i
 pgrep -P $$ read || break  # stop waiting if read has finished
done
 pgrep -P $$ read && pkill -P $$ read
 

Thanks
Hopefully the same should appply to cd command?

you dont want to start cd in background ?

I do!!!

smoking crack ?

The issue is in my system cd command hangs as the directories are not mounted properly.
This causes the cd command to hang.
The cd command is used in a script which should not fail .
I searched in forums how to timeout a command.
Hence wanna know Can we apply the same logic to cd command?
Please help

Problem is that cd is built into the shell and i cannot test this.
cd /etc &
[1] 20517
returns a pid that is not eq to $$ but i asume the name of pid 20517 is not cd rather than bash.

if this fails you can try the following
bash -c "cd /etc" & #test /etc
sleep 2
pgrep -P $$ bash || cd /etc && exit 1

Are you attempting to cd to a directory on a hard mounted NFS share or an automounted share?