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

Function Libraries का उपयोग

एक function library एक toolbox जैसा है जो आप garage में रखते हैं: आप अपने favorite tools एक file में डालते हैं और फिर वह पूरा box किसी भी दूसरी script से borrow करते हैं।

In this page:

  1. Function Libraries
Syntax
bash
source library_file.sh
function_from_library arguments

Function Libraries

Related functions को एक separate .sh file में group किया जा सकता है और source file.sh (या shorthand . file.sh) के साथ दूसरी script में load किया जा सकता है, उन्हें कई scripts में reusable बनाते हुए।

यह Bash का एक module import करने का equivalent है। Sourcing file को current shell में चलाता है, इसलिए इसके functions और variables directly available हो जाते हैं।

Note: source lib.sh और . lib.sh equivalent हैं — dot सिर्फ source का एक shorter alias है।

उदाहरण: Function Libraries

bash
#!/bin/bash
# Simulating a sourced library inline for this example
square() {
    echo $(( $1 * $1 ))
}

cube() {
    echo $(( $1 * $1 * $1 ))
}

echo "Square of 4: $(square 4)"
echo "Cube of 3: $(cube 3)"
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. source के लिए एक relative path उपयोग करना, इसलिए यह टूट जाता है जब script किसी दूसरी directory से चलाई जाए।
  2. Library file के अंदर ऐसा code डालना जो immediately चलता है।
  3. अलग-अलग libraries में functions को same नाम देना, इसलिए एक दूसरे को override कर देता है।

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.