Local Variables का उपयोग
एक local variable एक whiteboard जैसा है जो meeting खत्म होने पर wipe हो जाता है। इसकी value सिर्फ function के अंदर रहती है और कहीं और उपयोग किए labels को mess नहीं कर सकती।
In this page:
Syntax
function_name() {
local variable_name=value
}
Local Variables
Default रूप से, एक function के अंदर set किए variables global होते हैं और इसके बाहर वाले variables से clash कर सकते हैं।
local keyword एक variable को सिर्फ उस function call तक scope करता है, इसे caller के variables में leak होने या overwrite करने से रोकते हुए। किसी भी ऐसी चीज़ के लिए local उपयोग करना जो share करने के लिए नहीं है अच्छी practice है।
Warning:
local के बिना, एक function के अंदर assign किया गया variable silently किसी भी same-named global variable को overwrite कर देता है।उदाहरण: Local Variables
#!/bin/bash
message="global value"
show_message() {
local message="local value"
echo "Inside function: $message"
}
show_message
echo "Outside function: $message"
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. #}
आम गलतियां
localभूल जाना, इसलिए variables global scope में leak हो जाते हैं।local x=$(cmd)उपयोग करना औरcmdका exit status खो देना।localसे function के बाहर काम करने की उम्मीद करना, जो एक error देता है।
🔒
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