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

Local Variables का उपयोग

एक local variable एक whiteboard जैसा है जो meeting खत्म होने पर wipe हो जाता है। इसकी value सिर्फ function के अंदर रहती है और कहीं और उपयोग किए labels को mess नहीं कर सकती।

In this page:

  1. Local Variables
Syntax
bash
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

bash
#!/bin/bash
message="global value"

show_message() {
    local message="local value"
    echo "Inside function: $message"
}

show_message
echo "Outside function: $message"
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. local भूल जाना, इसलिए variables global scope में leak हो जाते हैं।
  2. local x=$(cmd) उपयोग करना और cmd का exit status खो देना।
  3. local से function के बाहर काम करने की उम्मीद करना, जो एक error देता है।

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.