Linux screen run script in background

Linux `screen` Command – Run in Background

The Linux screen command is extremely useful for the cases when you need to start a long-running process on a remote machine.

Even if your connection drops and the SSH session is terminated, with the screen command you can be sure that the process will keep running in the background and the “lost” terminal session can be resumed.

This note shows how install and how to use the Linux screen command to run a process in the background.

Cool Tip: How to Scroll Up while running the screen command! Read more →

Linux `screen` Command

Install the screen using one of the following commands, depending on your Linux distribution:

Start a screen session:

Press the space or return button to close the license agreement and continue to the screen shell, that looks just like a regular terminal window.

Am I Inside a “Screen”? An interface inside a screen session is exactly as the command prompt. To determine whether you are inside the screen or not, execute the echo $STY command. It returns the name of the screen you’re in. If it is null – you are inside the “real” terminal.

To start a named screen session, run:

To execute a command in the background but don’t attach to the screen session (useful for system startup scripts), run:

To terminate the current screen session (not put it into the background but close), press CTRL + D or type:

List the currently running screen sessions:

Reattach to the screen (resume the detached screen session):

To reattached to the the specific screen session, run:

Kill the specific screen session:

To kill all the screen sessions, run:

Cool Tip: Want to ROCK? Start a GUI (graphical) application on a remote Linux workstation over SSH!Read more →

Источник

Linux Scripts Running in the Background

This articles gives a brief explanation of running scripts in the background.

Foreground to Background

If you’ve started something in your session and it’s captured the session, you can move it to the background by issuing the ctrl+z bg commands.

  • ctrl+z : Stops the process. It doesn’t kill it.
  • bg : «bg» stands for background. This sends the current process to the background and releases your current command prompt.

It’s better to plan properly, but this is an easy way to switch from a foreground to background if you change your mind.

Run Scripts in the Background

A script can be run in the background by adding a «&» to the end of the script.

You should really decide what you want to do with any output from the script. It makes sense to either throw it away, or catch it in a logfile.

If you capture it in a log file, you can keep an eye on it by tailing the log file.

The script can still be affected by hang-up signals. You can stop this by using the nohup command. This will accept all standard output and standard error by default, but you can still use a custom log file.

Читайте также:  1с предприятие под linux

Checking Background Jobs

The jobs command lists the current background jobs and their state.

You can bring a job to the foreground by issuing the fg command for the job of interest.

Once in the foreground, it’s just like any other foreground process, and keeps hold of the shell until it completes.

Источник

Как запустить процесс в фоне Linux

Как правило, выполнение команд в терминале связано с одним неудобством — прежде чем приступить к вводу следующей команды, следует дождаться выполнения предыдущей. Это происходит, поскольку текущий процесс блокирует доступ к оболочке операционной системы и в таких случаях говорят, что команда выполняется на переднем плане. Что же делать, если нужно запустить несколько команд одновременно? Есть несколько решений. Первое и наиболее очевидное — открыть дополнительное окно терминала. Второе — инициировать выполнение команды в фоновом режиме.

Если какой-либо процесс происходит в фоновом режиме, это значит, что он не предусматривает взаимодействия с пользователем, следовательно, доступ к оболочке остается свободным. Прочитав эту статью, вы узнаете как запустить процесс в фоне Linux и что делать, чтобы их выполнение не прерывалось после закрытия терминала.

Как запустить процесс в фоне Linux

Для выполнения команды в фоновом режиме достаточно добавить в конце символ амперсанда (&):

В выводе терминала будут отображены порядковый номер задачи (в квадратных скобках) и идентификатор процесса:

В фоновом режиме можно одновременно запускать сразу два, три, четыре процесса и даже больше.

Работая в фоновом режиме, команда все равно продолжает выводить сообщения в терминал, из которого была запущена. Для этого она использует потоки stdout и stderr, которые можно закрыть при помощи следующего синтаксиса:

command > /dev/null 2>&1 &

Здесь >/dev/null 2>&1 обозначает, что stdout будет перенаправлен на /dev/null, а stderr — к stdout.

Узнать состояние всех остановленных и выполняемых в фоновом режиме задач в рамках текущей сессии терминала можно при помощи утилиты jobs c использованием опции -l:

Вывод содержит порядковый номер задачи, идентификатор фонового процесса, состояние задачи и название команды, которая запустила задание.

В любое время можно вернуть процесс из фонового режима на передний план. Для этого служит команда fg:

Если в фоновом режиме выполняется несколько программ, следует также указывать номер. Например:

Для завершения фонового процесса применяют команду kill с номером программы:

Как перевести процесс в фоновый режим

Если изначально процесс был запущен обычным способом, его можно перевести в фоновый режим, выполнив следующие действия:

  1. Остановить выполнение команды, нажав комбинацию клавиш Ctrl+Z.
  2. Перевести процесс в фоновый режим при помощи команды bg.

Работа процессов в фоне

Запуск скрипта в фоне linux — это одно, но надо чтобы он ещё работал после закрытия терминала. Закрытие терминала путем нажатия на крестик в верхнем углу экрана влечет за собой завершение всех фоновых процессов. Впрочем, есть несколько способов сохранить их после того как связь с интерактивной оболочкой прервется. Первый способ — это удаление задачи из очереди заданий при помощи команды disown:

Как и в предыдущих случаях, при наличии нескольких одновременно выполняемых процессов следует указывать номер того, относительно которого будет выполнено действие:

Убедиться, что задачи больше нет в списке заданий, можно, использовав уже знакомую утилиту jobs -l. А чтобы просмотреть перечень всех запущенных процессов (в том числе и отключенных) применяется команда

Второй способ сохранить запущенные процессы после прекращения работы терминала — команда nohup. Она выполняет другую команду, которая была указана в качестве аргумента, при этом игнорирует все сигналы SIGHUP (те, которые получает процесс при закрытии терминала). Для запуска команды в фоновом режиме нужно написать команду в виде:

Как видно на скриншоте, вывод команды перенаправляется в файл nohup.out. При этом после выхода из системы или закрытия терминала процесс не завершается. Существует ряд программ, которые позволяют запускать несколько интерактивных сессий одновременно. Наиболее популярные из них — Screen и Tmux.

  • Screen либо GNU Screen — это терминальный мультиплексор, который позволяет запустить один рабочий сеанс и в рамках него открыть любое количество окон (виртуальных терминалов). Процессы, запущенные в этой программе, будут выполняться, даже если их окна невидимы или программа прекратила работу.
  • Tmux — более современная альтернатива GNU Screen. Впрочем, возможности Tmux не имеют принципиальных отличий — в этой программе точно так же можно открывать множество окон в рамках одного сеанса. Задачи, запущенные в Tmux, продолжают выполняться, если терминал был закрыт.
Читайте также:  Установка openvpn linux ubuntu

Выводы

Чтобы запустить скрипт в фоне linux, достаточно добавить в конце знак &. При запуске команд в фоновом режиме отпадает необходимость дожидаться завершения одной команды для того, чтобы ввести другую. Если у вас возникли вопросы, обязательно задавайте их в комментариях.

Источник

How to Start Linux Command in Background and Detach Process in Terminal

In this guide, we shall bring to light a simple yet important concept in process handling in a Linux system, that is how to completely detach a process from its controlling terminal.

When a process is associated with a terminal, two problems might occur:

  1. your controlling terminal is filled with so much output data and error/diagnostic messages.
  2. in the event that the terminal is closed, the process together with its child processes will be terminated.

To deal with these two issues, you need to totally detach a process from a controlling terminal. Before we actually move to solve the problem, let us briefly cover how to run processes in the background.

How to Start a Linux Process or Command in Background

If a process is already in execution, such as the tar command example below, simply press Ctrl+Z to stop it then enter the command bg to continue with its execution in the background as a job.

You can view all your background jobs by typing jobs . However, its stdin, stdout, stderr are still joined to the terminal.

Run Linux Command in Background

You can as well run a process directly from the background using the ampersand, & sign.

Start Linux Process in Background

Take a look at the example below, although the tar command was started as a background job, an error message was still sent to the terminal meaning the process is still connected to the controlling terminal.

Linux Process Running in Background Message

Keep Linux Processes Running After Exiting Terminal

We will use disown command, it is used after the a process has been launched and put in the background, it’s work is to remove a shell job from the shell’s active list jobs, therefore you will not use fg , bg commands on that particular job anymore.

In addition, when you close the controlling terminal, the job will not hang or send a SIGHUP to any child jobs.

Let’s take a look at the below example of using diswon bash built-in function.

Keep Linux Process Running After Closing Terminal

You can also use nohup command, which also enables a process to continue running in the background when a user exits a shell.

Put Linux Process in Background After Closing Shell

Detach a Linux Processes From Controlling Terminal

Therefore, to completely detach a process from a controlling terminal, use the command format below, this is more effective for graphical user interface (GUI) applications such as firefox:

In Linux, /dev/null is a special device file which writes-off (gets rid of) all data written to it, in the command above, input is read from, and output is sent to /dev/null.

As a concluding remark, provided a process is connected to a controlling terminal, as a user, you will see several output lines of the process data as well as error messages on your terminal. Again, when you close the a controlling terminal, your process and child processes will be terminated.

Читайте также:  Samsung clp 360 драйвер windows 10

Importantly, for any questions or remarks on the subject, reach us by using the comment form below.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Linux: Start Command In Background

[donotprint]

Tutorial details
Difficulty level Easy
Root privileges No
Requirements Bash/ksh
Linux
Est. reading time 10m

[/donotprint]

Syntax

You can put a task (such as command or script) in a background by appending a & at the end of the command line. The & operator puts command in the background and free up your terminal. The command which runs in background is called a job. You can type other command while background command is running. The syntax is:

Examples

Put the ls command in the background, enter:
$ ls *.py > output.txt &
Put the following find command in a background by putting a ‘&’ at the end of the command line:

Fig.01: Linux background job in action (click to enlarge)

How do I see jobs running in the background?

Type the following command:
jobs
Sample outputs:

To see process IDs for JOB IDs in addition to the normal information pass the -l option:
jobs -l
Sample outputs:

To see process IDs only, enter:
jobs -p
Sample outputs:

How do I kill the jobs running in the background?

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

How do I bring process running in the background to the foreground?

The syntax is:
%JOB-ID
OR
fg JOB-ID
First, list the current jobs with jobs command, enter:
jobs -l
Sample outputs:

To bring the job id #2 to the foreground, enter:
%2
OR use fg command:
fg 2
Sample outputs:

To send back this job in the background hit CTRL-Z i.e. while holding the CTRL key, press z key. This will suspend the current foreground job. Type the following command to send back the job in the background:
%2 &
OR use bg command:
bg
The grep command job is now running in the background.

Summary of all useful commands

Description Command
To see which jobs are still running jobs jobs
jobs -l
ps aux
To put a command / script to the background command &
/path/to/command &
/path/to/script arg1 &
To bring a background job to the foreground fg n
%n
To send a job to the background without canceling it bg n
%n &

Note: n == Job id (use jobs command to see job id)..

See also:
  • Putting jobs in background from the Linux shell scripting tutorial.
  • Command examples pages: jobs command, bg command, and fg command
  • Man pages: ksh(1)

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

Оцените статью