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

Return Values क्या हैं

एक function का return एक gift से ज़्यादा एक thumbs up या thumbs down जैसा है। यह एक छोटा success-or-failure number देता है, इसलिए अगर आपको असली answers चाहिए तो function को उन्हें print करना होगा।

In this page:

  1. Return Values
Syntax
bash
function_name() {
  commands
  return status_code
}
function_name
echo "$?"

Return Values

एक Bash function में return इसका exit status (0-255) set करता है, वैसे ही जैसे एक script खुद exit होती है — यह दूसरी languages में return value जैसा arbitrary data *नहीं* return करता।

एक computed value "return" करने के लिए, functions typically इसे echo करते हैं और caller इसे $(function_name) से capture करता है। return न लिखने पर function का exit status इसके आखिरी executed command का हो जाता है।

Warning: return values 0–255 integers तक सीमित हैं — आप directly एक string या एक बड़ा number return नहीं कर सकते।

उदाहरण: Return Values

bash
#!/bin/bash
is_even() {
    if (( $1 % 2 == 0 )); then
        return 0
    else
        return 1
    fi
}

add() {
    echo $(( $1 + $2 ))
}

if is_even 4; then
    echo "4 is even"
fi

sum=$(add 3 5)
echo "Sum: $sum"
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. return से एक string return करने की कोशिश करना, जब यह सिर्फ 0 से 255 तक का एक exit status return करता है।
  2. $(func) से output capture करना और यह भूल जाना कि print हुई कोई भी चीज़ result बन जाती है।
  3. $? को बहुत late check करना, एक और command चलने के बाद।

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.