← Back to Bash Course | Chapter 10: Text Processing Tools | Lesson 8 of 12

trap कमांड

trap एक safety net लगाने जैसा है जो तब बजता है जब कुछ surprising होता है, जैसे कोई Ctrl+C press करे, ताकि आपका script जाने से पहले tidy up कर सके।

In this page:

  1. trap
Syntax
bash
trap 'commands_or_function' SIGNAL

trap

trap एक command या function को register करता है जो एक specific signal मिलने पर चलेगा, जैसे SIGINT (Ctrl+C) या EXIT (जब भी script किसी भी कारण से खत्म हो)।

trap cleanup EXIT एक common pattern है यह guarantee करने के लिए कि cleanup code हमेशा चले। Traps उन scripts के लिए essential हैं जो temp files या background jobs को reliably clean up करती हैं।

Note: trap cmd EXIT हर exit path पर चलता है — normal completion, एक error, या एक signal — इसे guaranteed cleanup के लिए ideal बनाते हुए।

उदाहरण: trap

bash
#!/bin/bash
cleanup() {
    echo "Cleaning up before exit..."
}

trap cleanup EXIT

echo "Doing some work..."
echo "Script is about to finish"
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. वे signals trap करना जो catch नहीं किए जा सकते, जैसे SIGKILL।
  2. trap command को quote करना भूल जाना, इसलिए यह बहुत जल्दी expand हो जाता है।
  3. SIGINT के लिए एक trap के अंदर exit न करना, इसलिए Ctrl+C के बाद script continue रहता है।
🔒

Chapter Quiz — Complete all 12 topics to unlock

0/12 topics done

Complete these topics first:

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.