trap कमांड
trap एक safety net लगाने जैसा है जो तब बजता है जब कुछ surprising होता है, जैसे कोई Ctrl+C press करे, ताकि आपका script जाने से पहले tidy up कर सके।
In this page:
Syntax
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
#!/bin/bash
cleanup() {
echo "Cleaning up before exit..."
}
trap cleanup EXIT
echo "Doing some work..."
echo "Script is about to finish"
Login to try C/C++/Java/PHP code in the editor
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. #}
आम गलतियां
- वे signals trap करना जो catch नहीं किए जा सकते, जैसे
SIGKILL। - trap command को quote करना भूल जाना, इसलिए यह बहुत जल्दी expand हो जाता है।
SIGINTके लिए एक trap के अंदर exit न करना, इसलिए Ctrl+C के बाद script continue रहता है।
🔒
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: