Bash – Queue Up Commands While One Command is Executing

bashcommand lineshell

Suppose you run a command which takes some time to return and want to execute a different command after it has been executed but you didn't plan this in advance.

I know that there is the option to press Ctrl + Z and then submit fg && otherCommand. However, this has two major flaws:

  1. It doesn't work if the first command is a composition of different commands (command1 && command2 or command1; command2) because then the subsequent commands of the first submitted line aren't executed.
  2. Execution of the first command is stopped while you enter the next command. With those nasty 30 second commands, the time you spend entering the next command makes up a good portion of the remaining execution time, if not all of it.

I also know that you can just type in the next command while one command is being executed and then hit Enter to sumbit it. However, this also has two major flaws:

  1. It doesn't work if the command you execute first reads from stdin.
  2. If the command you execute first produces output, you can't see what you entered.

Is there a quick way to queue up more commands while one command is being executed, possibly involving using a special terminal emulator or several terminals?

Best Answer

Press Ctrl+Z and immediately run bg. This causes the current command to keep running in the background. Then you can use fg && otherCommand to schedule otherCommand after the current one.

To make this easier, I've configured Ctrl+Z in my shell to run bg when I press it on an empty command line. See In zsh, how can I more quickly disown the foreground process? and How do you send command line apps directly to the background? ; I haven't checked if modern versions of bash make it easy to do the same.