← Back to Bash Course | Chapter 2: Variables & Types | Lesson 7 of 13

readonly Variables का उपयोग

एक readonly variable pencil की बजाय permanent marker से लिखने जैसा है: एक बार लिख देने पर आप इसे erase या change नहीं कर सकते, और कोशिश करने पर computer complain करता है।

In this page:

  1. readonly Variables
Syntax
bash
readonly VARIABLE_NAME=value

readonly Variables

एक variable को readonly mark करना इसे बाद में reassign होने से रोकता है, कुछ इसे change करने की कोशिश करने पर एक error cause करते हुए। यह उन constants के लिए useful है जिन्हें कभी accidentally overwrite नहीं होना चाहिए।

एक बार readonly set होने पर, एक variable script की बची execution के लिए ऐसा ही रहता है।

Warning: एक readonly variable को reassign करने की कोशिश silently fail नहीं होती — यह stderr पर एक error print करती है।

उदाहरण: readonly Variables

bash
#!/bin/bash
readonly PI=3.14159
echo "Pi is $PI"

PI=3.14  # this will produce an error
echo "This line may not run depending on the shell"
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. एक readonly variable को change या unset करने की कोशिश करना, जो एक error देता है।
  2. यह उम्मीद करना कि readonly variable को child processes के लिए available बनाता है, जिसके लिए export चाहिए।
  3. एक variable को इसकी final value assign करने से पहले readonly declare करना, इसलिए इसे बाद में set नहीं किया जा सकता।

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.