Recursive Functions का उपयोग
एक recursive function दो mirrors के बीच खड़े होने, या Russian nesting dolls के एक set जैसा है: हर call एक छोटी doll खोलता है जब तक यह सबसे छोटी doll तक न पहुंच जाए, जो stopping point है।
In this page:
Syntax
function_name() {
if [ base_case ]; then
return
fi
function_name arguments
}
Recursive Functions
एक Bash function अपने आप को call कर सकता है, बिल्कुल किसी भी दूसरी language की तरह recursion produce करते हुए, जब तक एक base case हो जो recursion को रोके।
हर recursive call उसी shell में चलता है लेकिन अपने खुद के local variables के set के साथ। Bash के पास system stack से आगे कोई built-in recursion depth limit protection नहीं है, इसलिए deep recursion risky हो सकता है।
Note:
हमेशा पहले एक clear base case define करें — इसके बिना, एक recursive Bash function crash होने तक चलता रहेगा।
उदाहरण: Recursive Functions
#!/bin/bash
factorial() {
local n=$1
if (( n <= 1 )); then
echo 1
else
local prev=$(factorial $((n - 1)))
echo $(( n * prev ))
fi
}
echo "5! = $(factorial 5)"
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. #}
आम गलतियां
- एक base case भूल जाना, जो shell fail होने तक endless recursion बनाता है।
- Variables के लिए
localउपयोग न करना, इसलिए recursive calls एक-दूसरे की values overwrite कर देते हैं। - Deep recursion से fast होने की उम्मीद करना, जब Bash functions धीमे और depth में limited हैं।
🔒
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first:
- Function Basics
- The read Command and Here-Strings
- Function Arguments
- stdin, stdout, stderr and File Descriptors
- Return Values
- Redirection Operators
- Local Variables
- Pipes and Chaining Commands
- Recursive Functions
- Here-Documents (<<EOF)
- Function Libraries
- The tee Command
- Discarding Output with /dev/null