Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I was trying the following combination in order to get the pid of the ssh session (running in the background displays the pid) and than fg to get back to the ssh session and introduce the password:

ssh targetHost &; fg

I get the following error:

-bash: syntax error near unexpected token `;'

Why does the ";" not work to as expected in this case?

My aim is to start a ssh session and know its pid and I need to do this in as few lines as possible. I need to start several ssh sessions, put them in the background and at the end kill them - that's why I need the pids.

share|improve this question
2  
ssh targetHost & pid=$!; echo "$pid" –  val0x00ff Sep 30 '13 at 15:14
add comment

3 Answers

up vote 1 down vote accepted

You are mixing up two different cases:

  • foo ; bar will run foo, wait for it to finish and then run bar
  • foo & bar will start foo, put it in background and start bar directly afterwards.

You have to decide, either use the one or the other. You cannot do both. ;)

To solve you problem, you can simply run all jobs in background and then use job to list the pids:

michas@lenny:~$ sleep 10 &
[1] 18007
michas@lenny:~$ sleep 10 &
[2] 18011
michas@lenny:~$ sleep 10 &
[3] 18015
michas@lenny:~$ sleep 10 &
[4] 18019
michas@lenny:~$ sleep 10 &
[5] 18026
michas@lenny:~$ jobs -p
18007
18011
18015
18019
18026
michas@lenny:~$ 

You also do not necessarily need the pids to send kill signals. For example kill %1 will kill the first background process.

share|improve this answer
add comment

&; is always wrong. If you want to run things in the background in a compact one-liner, omit the ';' entirely and simply use & between commands.

for i in ./*; do my_command "$i" & done

# see http://mywiki.wooledge.org/BashPitfalls

share|improve this answer
add comment

Others have already explained why &; fails. I wanted t =o point out that the PID of the last backgrounded process is saved as $!. You can, therefore, always access the PID of the last command :

ssh targetHost & echo $!; fg

As for killing them, you can kill all ssh sessions with this command:

pkill -x ssh

The x causes pkill and pgrep to match the full command name, this ensures you won't kill sshd or ssh-agent. If you only want to kill connections to a specific machine, you could also do this:

pkill $(pgrep -alx ssh | grep TARGET_IP | cut -d ' ' -f 1)
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.