How to plan a task to run after another already running task in bash?

Generally what I do is: Ctrl+Z fg && command2

  1. Ctrl+Z to pause it and let you type more in the shell.
  2. Optionally bg, to resume command1 in the background while you type out command2.
  3. fg && command2 to resume command1 in the foreground and queue up command2 afterwards if command1 succeeds. You can of course substitute ; or || for the && if you so desire.

  1. start a command

    command1
    
  2. pause the execution by pressing Ctrl+Z

  3. find the job number of the paused command (it's usually already printed to console when to console when to command is paused) by executing

    jobs
    
  4. let command1 continue in background

    bg
    
  5. plan execution of command2 to await finish of command1

    wait -n <command1 job number> ; command2
    

Documentation Job Control Builtins


There are several alternatives.

  • With one ampersand, 'push to background', the second program starts after the first one starts, but they will probably run alongside each other.

    command1 & command2
    
  • With two ampersands, 'logical and', the second program will start only if the first program finished successfully.

    command1 && command2
    
  • With a semicolon separating the commands in the command line, the the second program will start, when the first program finished, even if it failed or was interrupted.

    command1 ; command2
    
  • You can use wait <PID> to wait for the first command to finish, if it is already running from the same shell (in the same terminal window).

  • Otherwise if the first command is already running from another shell (in another window), you can use a small while loop using ps to check if the PID is still found by ps. When it is no longer found, the second command will be started.

    This demo example for bash checks if top is running via the PID, and runs the command

    echo "*** $USER, I am ready now ***"
    

    if/when top is no longer running.

    pid=$(ps -A|grep top|cut -d ' ' -f 1); \
    while [ "$pid" != "" ]; do ps -A|grep "$pid" > /dev/null; \
    if [ $? -eq 0 ]; then sleep 5;else pid=""; fi; done; \
    echo "*** $USER, I am ready now ***"