Kill first command as soon as second exits

3

I've been looking for best practice for this scenario for a long time.

If I have process2 that depends on process1 running beforehand. I set up an alias like:

alias both='process1 & process2'

Then, when process2 exits, I would like for process1 to exit as well (my current solution is to go back to the terminal and kill %%).

For example (to connect to an iOS device from mac over usb):

alias usbssh='/usr/local/bin/iproxy 2222 22 & ssh -p 2222 root@localhost'

How do I keep iproxy running, and kill it as soon as ssh exits?

Elist

Posted 2017-06-21T07:11:27.737

Reputation: 133

Just seperately, do you have more info, re: Connecting to iOS over USB, via SSH? – voices – 2017-06-21T11:29:18.213

@tjt263 - obviously only works for jailbroken devices... – Elist – 2017-06-21T11:44:36.680

@tjt263, I really don't get what you are asking me. Can you please say explicitly what info you are after? – Elist – 2017-06-21T20:54:07.793

Don't think I can make it much simpler than that.. I've never heard of iproxy or ssh over USB and I'm just curious. I don't even really know enough about it to be more specific. – voices – 2017-06-21T21:08:10.980

Ok. iproxy is a utility to port forward local port to a port on an apple mobile device connected via usb. It is a part of the open source libimobiledevice project. In the exaple above, localhost:2222 is forwarded to port 22 on the connected iphone. The iPhone has an ssh daemon listening on port 22. Anything else you want me to expand on? – Elist – 2017-06-22T04:42:57.533

Answers

4

Just append kill $! to the end: process1 & process2; kill $!

$! is a variable (confusingly known as a "parameter" in Bash), and will expand to the last background PID anywhere:

Expands to the process ID of the job most recently placed into the background, whether executed as an asynchronous command or using the bg builtin (see JOB CONTROL below).

%% is special, and will only expand to the last background PID in the context of shell built-in commands like fg and kill. Unfortunately this isn't clear from the man page:

The symbols %% and %+ refer to the shell's notion of the current job, which is the last job stopped while it was in the foreground or started in the background.


PS: If you need to make this a command string, make sure kill $! is single-quoted so it's expanded at runtime. Even better, write a function instead of an alias to avoid their limitations.

l0b0

Posted 2017-06-21T07:11:27.737

Reputation: 6 306

Great! actually, it is much easier then I thought... BTW, can you explain $! vs %%? – Elist – 2017-06-21T07:21:31.390

Excellent; I agree, re: function>alias. – voices – 2017-06-21T11:21:52.383