Bash variable scope

Source: Internet
Author: User
Tags variable scope

Bash has two types of scopes: Global scopes, namely the declared variables by default, and local scopes.

1) global variable declaration involves the following situations:

#!/bin/bashmm=12 #visible globallyfunc() {    mn=34  #visible globally    echo "mc=${mc}" #is visible}mc=35  #visible globally# echo "mn={$mn}"  #is not visiblefuncecho "mm=${mm};mn=${mn};mc=${mc}"

However, the global variable Mn declared in the function is invisible before the main function is called.

2) local scope: When declaring a variable, add the local keyword before and apply it only to the function. Its scope
Only visible in the current function block and Its subfunctions.

#!/bin/bashfunc1() {    local loc1=11    echo "func1 loc1=${loc1}" #is visible}func2() {    echo "func2 loc1=${loc1}"  #is visible}func1echo "local loc1:${loc1}" #not visible

There is a special case: when the Declaration of local variables and the setting is in a single command line, the operation order is displayed, the variable is set first,
Then, limit the scope of the variable. This result is reflected in the return value.
As follows:

#!/bin/basht=$(exit 1)echo $?  #  return 1echo "t=${t}"func() {    t1=$(exit 1)    echo $?     #  return 1    echo "t1=${t1}"    local t2=$(exit 1)    echo $? #  return 0    echo "t2=${t2}"    local t3    t3=$(exit 1)    echo $?  #  return 1    echo "t3=${t3}"}func()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.