Wait linux command line

Команда wait в Bash

wait — это команда, которая ожидает завершения заданных заданий и возвращает статус выхода ожидаемой команды.

Поскольку команда wait влияет на текущую среду выполнения оболочки, в большинстве оболочек она реализована как встроенная команда.

В этой статье мы рассмотрим встроенную команду wait

Команда wait Bash

Общий синтаксис wait имеет следующий вид:

ID — это идентификатор процесса или задания. Если ID не указан, команда ожидает завершения всех дочерних фоновых заданий.

Команда wait возвращает статус выхода последней ожидаемой команды.

Например, чтобы дождаться фонового процесса с PID 7654 , вы должны использовать:

Когда задано несколько процессов, команда ожидает завершения всех процессов.

Задания указываются с использованием спецификации задания («спецификация задания»), которая является способом ссылки на процессы, составляющие задание. Спецификация задания начинается с символа процента, за которым следует номер задания ( %n ). Вот пример:

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

Чтобы дождаться задания, запустите команду wait за которой следует спецификация задания:

При вызове с параметром -n команда ожидает завершения только одного задания из заданных pid или заданий и возвращает статус завершения. Если аргументы не указаны, wait -n ожидает завершения любого фонового задания и возвращает статус завершения задания.

В приведенном выше примере wait -n выводит только статус возврата задания, которое завершается первым; он не показывает PID задания. Если вы хотите получить идентификатор задания или спецификацию задания, для которого возвращается статус выхода, используйте параметр -p чтобы присвоить его переменной:

wait -p job_id -n 45432 54346 76573

-p был представлен в Bash 5.1. Если вы используете старую версию Bash, вы получите ошибку «неверный вариант».

Параметр -f сообщает wait чтобы дождаться фактического завершения каждого pid или jobpec, прежде чем возвращать свой код выхода, вместо того, чтобы возвращаться при изменении статуса задания. Эта опция действительна, только если включено управление заданиями. По умолчанию управление заданиями включено только для интерактивных запросов.

Примеры

wait обычно используется в сценариях оболочки, которые порождают дочерние процессы, выполняющиеся параллельно.

Чтобы проиллюстрировать, как работает команда, создайте следующий сценарий:

#!/bin/bash sleep 30 & process_id=$! echo "PID: $process_id" wait $process_id echo "Exit status: $?" 

Давайте объясним код построчно:

  1. Первая строка называется shebang и сообщает операционной системе, какой интерпретатор использовать для анализа остальной части файла.
  2. Мы используем команду sleep для имитации трудоемкого фонового процесса.
  3. $! — это внутренняя переменная Bash, в которой хранится PID последнего задания, запущенного в фоновом режиме. В этом примере это PID команды перехода в sleep . Мы сохраняем PID в переменной ( process_id ).
  4. Печатает номер PID.
  5. PID передается команде wait которая ожидает завершения команды sleep
  6. Печатает статус выхода команды wait . $? — это внутренняя переменная Bash, которая содержит статус выхода последней выполненной команды.
Читайте также:  Debian дистрибутив gnu linux

Если вы запустите сценарий, он напечатает что-то вроде этого:

Вот пример использования опции -n

#!/bin/bash sleep 3 & sleep 30 & sleep 5 & wait -n echo "First job completed." wait echo "All jobs completed." 

Когда скрипт выполняется, он порождает 3 фоновых процесса. wait -n ожидает завершения первого задания и вывода оператора echo. wait ожидает завершения всех дочерних фоновых заданий.

first job completed all jobs completed 

Последний пример объясняет параметр -f . Откройте терминал и запустите:

Откройте другой терминал и остановите процесс командой kill :

После изменения статуса процесса команда wait завершится и вернет код завершения процесса.

Теперь повторите те же шаги, но на этот раз используйте wait -f $pid :

Остановите процесс с другого терминала:

На этот раз команда wait не завершится. Он будет работать до тех пор, пока не sleep процесс.

Вывод

Команда wait ожидает завершения указанных заданий и возвращает код завершения задания.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

Bash wait Command with Examples

The bash wait command is a Shell command that waits for background running processes to complete and returns the exit status. Unlike the sleep command, which waits for a specified time, the wait command waits for all or specific background tasks to finish.

This tutorial explains the wait command syntax and provides example bash script codes.

Bash wait Command with Examples

  • Access to the command line/terminal.
  • Administrator (sudo) privileges.
  • A text editor, such as Vim or Nano.

Note: You might also find useful our guide on how to run a bash script that features several different techniques.

bash wait Command Syntax

There are different ways to use the wait command in bash scripts. The table below explains each use case.

Command Explanation
wait Without any parameters, the wait command waits for all background processes to finish before continuing the script.
wait An added PID or job ID waits for a specific process to end before continuing the script.
wait -n Waits for only the following background process to complete and returns an exit status.
wait -f Terminating a program first waits for the background task to finish before quitting.

Wait Command Examples

There are three additional parameters to know when working with wait in bash scripts:

1. The ampersand sign ( & ) after a command indicates a background job.

2. $! fetches the PID of the last background process. Store the previous PID in a variable when working with multiple background processes.

3. $? prints the exit status of the last process.

To see how these three parameters work together, open a terminal window and run:

Terminal output of the PID and exit status of a background process

The $! parameter stores the background process PID, while $? stores the exit status. The exit status 0 indicates the command finished successfully.

Single Process wait Example

1. Start by opening the terminal and create a simple background process:

2. Confirm the job is running in the background with:

Note: If the job shows as complete, try to change the sleep time to more than 10 seconds.

3. Use the wait command without any parameters to pause until process completion:

Terminal output of wait command

The terminal waits for the background process to finish.

Terminal output of wait command done process

After 10 seconds (due to sleep 10 ), the console prints a Done message.

Single Process bash wait Example

Use the wait command to indicate by what point a background process must execute inside a script.

1. For example, add the following code in a text editor:

#!/bin/bash echo Background process & echo First message echo Second message wait echo Third message 

Single process wait bash script example

If the background process does not finish the first and second process, the wait command invokes a pause to wait for the background process to complete after the second process before continuing to the third process.

2. Save the script as single_process.sh. In the terminal, change permissions to make the script executable:

sudo chmod +x single_process.sh

Output of single process script

The background process completes any time before the wait command, and the script continues.

Multiple Processes wait Example

1. Open the text editor and add the following script with multiple processes:

#!/bin/bash sleep 10 & sleep 15 & sleep 5 & echo $(date +%T) wait echo $(date +%T)

Multiple processes wait bash script

The script prints the current time before and after the wait command. Without any parameters, the program waits for all processes to finish.

2. Save the script as test.sh and close the file. Next, make the script executable:

3. Lastly, run the program with:

Output of multiple processes bash script

Since the processes run in the background, all three are completed in fifteen seconds.

4. Use the same script to test the following use cases:

  • Add the -n parameter to wait . Only the fastest process completes, and the script ends in ten seconds.
  • Add the job ID to indicate for which job the script should wait. For example, wait %1 pauses for process 1 ( sleep 10 ) to complete.

Multiple Processes bash wait With PID Example

1. When working with multiple processes, use the PID to identify a process. The example script below displays a single use case:

#!/bin/bash echo "Process 1 lasts for 2s" && sleep 2 & PID=$! echo "Process 2 lasts for 3s" && sleep 3 & echo "Current time $(date +%T)" wait $PID echo "Process 1 ended at time $(date +%T) with exit status $?" wait $! echo "Process 2 ended at time $(date +%T) with exit status $?" 

Multiple processes wait bash script with PIDs

2. Save the script as multi_wait.sh. Make the script executable with:

sudo chmod +x multi_wait.sh

3. Run the script to see the output:

Output of multiple processes wait bash script with PIDs

The script takes two seconds to complete the first process (due to sleep 2) and three seconds to complete the second process. The two processes are executed simultaneously and both complete in three seconds.

Hopefully, the examples helped you learn how to use the wait command in bash scripts and what output to expect when working with single and multiple background processes. Next, use our Bash Function guide to reduce repetitive code and speed up your scripting.

Источник

Bash Wait command in Linux

The wait is a Linux command that returns an exit status after waiting for a complete running process. When several processes are running simultaneously, the wait command can only keep track of the last one. If the wait command is not associated with a job or process ID, it will wait for all child processes to complete before returning an exit status. The bash wait command is often used with the process IDs or Job IDs command.

In this tutorial, we will explore the Bash Wait Command in Linux.

Syntax:

The general syntax of the Wait command in Linux is:

wait [option] ID

ID would be a process ID or Job ID.

Explaining Bash Wait Command in Linux:

First, create a file by using the touch command:

Make this file executable by using the below command:

Once the executable privileges are granted to the file, open the file and write a script in bash file:

$! is a variable in BASH that stores the PID of the most recent process.

Now, run the script as follows:

Process ID and Exist status will appear in the shell.

Using –n option:

With the –n option, the wait command only waits for a single job from the provided process ID or job specs to finish before returning its exit status. Wait -n waits for any background job to finish and returns the job exit status if no arguments are provided.

Write the below-given lines in your script:

echo «First job has been completed.»

echo «All jobs have been completed.»

Next, run the script again and when the first job is completed, it will print the message on the terminal and wait for all other jobs to be completed.

Using –f option:

The -f option waits for each process id or job to stop before returning the exit code. Job control is available only for responsive prompts by default.

Open terminal and run command:

Open a different terminal window and execute the kill command to terminate the process.

The status will be changed. The Wait command will complete and return the process exit code.

Repeat the above-given steps with the –f command.

Script with Wait command:

We are using ‘hello.sh’ and ‘bash.sh’ scripts for demonstration. The ‘ hello.sh’ script prints numbers from 1 to 5, and ‘bash.sh’ script calls hello.sh and runs it in the background, having the PID of hello.sh and waiting for it to end.

Create two scripts with the name hello and bash:

Add the below-given lines in the hello.sh file:

for i in 1 2 3 4 5 6 7 8 9 10

echo “hello.sh – Loop number $i .”

Add the below-given lines in the bash script:

Output:

Conclusion:

When a user wants to stop a process, the system releases all resources kept by the process and waits for another to start. We’ll need to notify the process that it can restart execution once the other processes are completed. The wait command in bash waits to complete the execution and returns the exit status when the process execution is complete. In this manual, we have seen some examples of the Bash wait command in Linux.

About the author

Aqsa Maqbool

As a Software engineer, I am passionate to write about various IT related
articles but have deep interest in Linux. I spend most of my time reading Linux related blogs and IT related books. I want to serve the world with my writing skills.

Источник

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