← Back to Bash Course | Chapter 11: Process Management | Lesson 3 of 12

wait कमांड

wait एक script को तब तक pause करता है जब तक एक या ज़्यादा background jobs जो इसने शुरू किए थे असल में run होकर खत्म नहीं हो जाते।
Syntax
bash
command &
pid=$!
wait "$pid"
wait

Waiting for a Specific Job

wait pid script को उस particular background process के खत्म होने तक block करता है, और फिर wait खुद उस process का exit status return करता है, जो $? में available हो जाता है।

उदाहरण: Waiting for a Specific Job

bash
#!/bin/bash
(exit 3) &
pid=$!
wait "$pid"
echo "background job exited with status $?"

Waiting for All Background Jobs

बिना किसी arguments के wait call करना तब तक block करता है जब तक current shell द्वारा शुरू किया गया हर background job पूरा न हो जाए, चाहे उनकी संख्या कुछ भी हो।

उदाहरण: Waiting for All Background Jobs

bash
#!/bin/bash
for i in 1 2 3; do
    ( sleep 0.05; echo "job $i done" ) &
done
wait
echo "all jobs finished"

Collecting Multiple Exit Statuses

कई background jobs के individual result check करने के लिए, हर PID save करें और उन पर एक-एक करके wait करें, क्योंकि बिना arguments वाला एक bare wait सिर्फ यह बताता है कि सब कुछ खत्म हो गया, हर job का individual outcome नहीं।

उदाहरण: Collecting Multiple Exit Statuses

bash
#!/bin/bash
(exit 0) &
pid_ok=$!
(exit 1) &
pid_bad=$!

wait "$pid_ok"
echo "first job status: $?"
wait "$pid_bad"
echo "second job status: $?"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. बिना arguments के wait call करना और यह मान लेना कि यह सिर्फ last job के लिए wait करता है; बिना arguments के यह सभी currently running background jobs के लिए wait करता है।
  2. यह भूल जाना कि wait $pid उस job का असली exit status return करता है, जिसे तुरंत capture न करने पर track करना आसान नहीं रहता।
  3. एक ऐसे PID पर wait करने की कोशिश करना जो current shell का direct child नहीं था (उदाहरण के लिए, एक पूरी तरह अलग process का PID), जो fail होता है क्योंकि wait सिर्फ shell के अपने child jobs पर काम करता है।
चैप्टर सारांश
  • बिना arguments के wait तब तक block करता है जब तक current shell द्वारा शुरू किया गया हर background job खत्म न हो जाए।
  • wait pid एक specific job के लिए wait करता है और इसका exit status wait के अपने exit status के रूप में return करता है।
  • wait सिर्फ उन processes पर उपयोग किया जा सकता है जो current shell के direct children हैं।
  • wait pid के ठीक बाद $? capture करना आपको backgrounded command का असली exit code देता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.