In this tutorial, we will explore the Bash 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:
sleep 3 &
processID=$!
echo "PID: $processID"
wait $processID
echo "Exit status: $?"
$! is a variable in BASH that stores the PID of the most recent process.
Now, run the script as follows:
$ ./BashWait.sh
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:
sleep 30 &
sleep 8 &
sleep 7 &
wait -n
echo "First job has been completed."
wait
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:
Wait for process 3944.
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
do
echo “hello.sh – Loop number $i.”
done
Add the below-given lines in the bash script:
echo “Started bash.sh”
echo “Started hello.sh”
./hello.sh &
process_id=$!
wait $process_id
echo “Completed hello.sh
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.
from Linux Hint https://ift.tt/3tX3lCn
0 Comments