Skip to content

Executing a linux command in background/foreground using terminal

Executing a Linux command silently or in background

  • While working on terminal we can make a command to execute in background, so that we can work something else on that terminal.
  • There are two ways to do it.

    Directly executing the command using & operator.

    COMMAND &
    
    vlc &
    

    Second method:

    • Run command
      my_command
      
    • Press CTRL+Z - This will pause(stop) the command.

    • To view the number assigned to the above command, use “jobs” command.

      $ jobs
      [n]+   Stopped             my_command &
      
    • It will show the number assigned to that job/command(it would be n here).

    • Now execute the command to run it in background

      $bg %n
      
    • Now you can check that it is running, using job command.

      $ jobs
      [1]+  Running                 my_command &
      

    Example

    $ vlc
    CTRL+Z
    $ jobs
    [1]+  Stopped                  vlc &
    $ bg %1
    $ jobs
    [1]+  Running                  vlc &
    

Executing command in foreground

  • Now when we execute a command silently, i.e, in background, Sooner or later we need to bring it back to foreground.

  • A job can be brought back to foreground as follows.

    • Check its job id

      $ jobs
      [n]+   Running                      COMMAND &
      
      $ jobs
      [1]+    Running                   vlc &
      
    • Now bring it to foreground

      $ fg %n
      
      $ fg %1
      
Back to top