Function Libraries का उपयोग
एक function library एक toolbox जैसा है जो आप garage में रखते हैं: आप अपने favorite tools एक file में डालते हैं और फिर वह पूरा box किसी भी दूसरी script से borrow करते हैं।
In this page:
Syntax
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
#!/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)"
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. #}
आम गलतियां
sourceके लिए एक relative path उपयोग करना, इसलिए यह टूट जाता है जब script किसी दूसरी directory से चलाई जाए।- Library file के अंदर ऐसा code डालना जो immediately चलता है।
- अलग-अलग libraries में functions को same नाम देना, इसलिए एक दूसरे को override कर देता है।
🔒
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