shell变量的可见性

注意:
后续谈到进程默认都是shell进程,也就是运行shell的进程。
一、前言

  • 执行脚本时,其实是在当前shell新建了另外一个子进程,由该子进程执行脚本指令。子进程会继承父进程的shell环境,脚本执行完该子进程也会被回收。
  • shell环境其实就是一个含有kv值的集合,包括环境变量和exported变量。
  • 进程执行的任何命令可以理解为子进程在执行一个个函数。而执行一个shell脚本就是创建一个新进程,里面的命令在这些新进程里执行。而为了让执行这些shell脚本就跟执行命令一样,不创建新进程,就在该进程里执行操作,可以用source(或者一个“.”)命令。

二、bash shell三种可见性级别的变量
按照可见性从小到大排序:
1.局部变量
local修饰符标识,只能在脚本的函数或者代码块中被访问,即使在该脚本内也不能访问到。

my_local_var="hello"
# Define a local variable inside a function
my_function() {
    
    
    local my_local_var="world"
    echo "Inside function: $my_local_var"    # prints "Inside function: world"
}

# Call the function and print the value of the local variable
my_function
echo "Outside function: $my_local_var"    # prints "Outside function: hello"

2. 普通(全局)变量
可以被整个脚本或者shell进程访问到,但是也仅此而已。子进程和父进程都访问不到。

-------------test1.sh-------------
#!/bin/bash
my_var=2
./test2.sh
echo "my_var_2=$my_var_2" #打印空

-------------test2.sh-------------
echo "test2 retrieving my_var=$my_var" #打印空
my_var_2=21
-------------test1.sh-------------
#!/bin/bash
my_var=2
source ./test2.sh
echo "my_var_2=$my_var_2" #打印空

-------------test2.sh-------------
echo "test2 retrieving my_var=$my_var" #打印2
my_var_2=21

3. exported变量
export修饰符标识,当把一个变量export时,他会把这个变量以key-value的形式添加到当前shell环境中。因此可以被子进程读取到,但是跟普通变量一样父进程读取不到该值。

-------------test1.sh-------------
#!/bin/bash
export my_export_var=1
./test2.sh
-------------test2.sh-------------
echo "test2 retrieving my_export_var=$my_export_var" #打印1
--------运行test1.sh的终端---------
echo $my_export_var #打印空

猜你喜欢

转载自blog.csdn.net/weixin_45719581/article/details/131866160