How set command in background,close terminal and get it back to fg?

Solution 1:

  1. Install screen:

    sudo apt-get install screen
    
  2. Start screen:

    screen -S session_name
    
  3. Execute your commands what you need.

  4. Detach screen from the terminal (your commands will be still running):

    Press CTRL+a+d

  5. Close the terminal

  6. Open another terminal and reattach the last screen session:

    screen -r
    

For more information and extra options for screen look in man screen.

Solution 2:

It's impossible in the way you want.

Let's review some basic concepts:

  • A process group is a collection of related processes which can all be signalled at once.
  • A session is a collection of process groups, which are either attached to a single terminal device (known as the controlling terminal) or not attached to any terminal.

If you closed the terminal, all the processes in the session are dead except those (daemons) reparented to the init process. And there's no way to give them a controlling terminal again.

In a word, process reparenting is highly restricted in POSIX systems (daemonizing is an exception) and your requirements can't be satisfied.

Solution 3:

Have you tried: byobu or tmux which are terminal multiplexers. Not exactly what you are looking for, but it has similar behavior.

byobu-screen

Then run your command, to detach:

byobu-screen -d

To resume:

byobu-screen -r

See https://help.ubuntu.com/community/Screen