0

I got 2 commands that run blocking the input in the console, so they must be ended with CTRL+C. I don't like running them in background, since I lost control for interruption. But otherwise I cannot execute them sequentially in a one-liner since first command waits for termination before next starts.

There must be a trick for this in unix. What I try is something like:

$ fg-wrapper infinite-cmd1 & infinite-cmd2
  Executing cmd1 in bg
  Executing cmd2 in bg
(Waiting for CTRL+C to end both)

I am searching for a oneliner, not an script: fg-wrapper is the built in posix command I would dream of provided as an example (I would like not having to script it)

Whimusical
  • 103
  • 4

1 Answers1

1

Try this:

#!/usr/bin/env bash

echo "Executing $1 in bg"
eval $1 &
echo "Executing $2 in bg"
eval $2 &
wait

Explanation:

$1 and $2 refer to the first and second argument in the command line. eval executes these commands with & running them in background. Finally, wait waits for these commands to terminate or they can be terminated with CTRL-C.

Try this script with ./script "ping google.com > /dev/null" "ping 127.0.0.1 > /dev/null"

Daniel
  • 151
  • 1
  • 6
  • Is it possible to have this in a one liner form, not in script? Would `eval cmd1 & eval cmd2 & wait` work? – Whimusical Jul 19 '19 at 09:40
  • Nope it does not work, it does not kill the bg processes – Whimusical Jul 19 '19 at 10:05
  • What commands are you testing with? Are you using your one-liner or the script? I have since tried `evince` and `chromium-browser` which both worked. – Daniel Jul 19 '19 at 13:35
  • With kubectl port-forwardinsg. Id like to open some of them and kill jointly with CTRL+C but with eval in the console, it just acts as if you executed bg, so the CTRL+C only applies to the wait. But I am using mingw on windows.. perhaps it has something to do.. – Whimusical Jul 19 '19 at 14:07
  • Ill end up with something like `sleep 3000 & sleep 4000 & wait && pkill sleep`, but I am sure it must exist a nice built-in way – Whimusical Jul 19 '19 at 14:09
  • 1
    The type of shell might come into play. I have only tested with bash in Ubuntu. Maybe someone can help further test this in different environments. – Daniel Jul 19 '19 at 14:24
  • Thanks Daniel! If noone suggestes better solution I will accept yours – Whimusical Jul 19 '19 at 14:38
  • 1
    This is a similar question. https://unix.stackexchange.com/questions/55558 Though the answer is similar. – Daniel Jul 19 '19 at 16:07
  • Thanks Daniel, the problem is that when commands execute from within script usually there's different mechanics – Whimusical Jul 19 '19 at 16:17