← Back to Bash Course | Chapter 8: Input/Output & Redirection | Lesson 9 of 13

Recursive Functions का उपयोग

एक recursive function दो mirrors के बीच खड़े होने, या Russian nesting dolls के एक set जैसा है: हर call एक छोटी doll खोलता है जब तक यह सबसे छोटी doll तक न पहुंच जाए, जो stopping point है।

In this page:

  1. Recursive Functions
Syntax
bash
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

bash
#!/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)"
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. एक base case भूल जाना, जो shell fail होने तक endless recursion बनाता है।
  2. Variables के लिए local उपयोग न करना, इसलिए recursive calls एक-दूसरे की values overwrite कर देते हैं।
  3. Deep recursion से fast होने की उम्मीद करना, जब Bash functions धीमे और depth में limited हैं।

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.