Scope
Global variable
#!/bin/bash

a=10

function f1()
{
	echo $a # 10, access global variable
	a=100 # by default, a is global variable
	echo $a # 100
	b=1000 # define a global variable
}

f1
echo $a # 100
echo $b # 1000
			
Local variable
#!/bin/bash

a=10

function f1()
{
	local a=1000 # define a local variable
	echo $a # 1000
}

f1
echo $a # 10
			
Variable between processes
  • In bash, variable scope is at the level of processes: each process has its own copy of all variables
  • # s3.sh
    #!/bin/bash
    
    a=10
    
    bash s4.sh # Print nothing
    
    export a # export a environmental variable
    
    bash s4.sh # 10
    			
    # s4.sh
    #!/bin/bash
    
    echo $a
    			
    Reference