十三、Shell篇——变量赋值、引用、作用范围

变量的定义

变量名的命名规则
 - 字母、数字、下划线
 - 不以数字开头

变量的赋值

为变量赋值的过程,称为变量替换
 变量名=变量值
  - a=123
 使用let为变量赋值
  - let a=10+20
 将命令赋值给变量
  - l=ls
 将命令结果赋值给变量,使用$ () 或者"
 变量值有空格等特殊字符可以包含在””或”中
 

 (1)将命令结果赋值给变量,使用$ () 或者"

~ % cmd1=`ls test/`
 ~ % cmd2=$(ls test/)
 ~ % echo $cmd1     
a.txt
aa.sh
b.txt
c.txt
d.txt
e.txt
 ~ % echo $cmd2
a.txt
aa.sh
b.txt
c.txt
d.txt
e.txt

(2)变量值有空格等特殊字符可以包含在””或”中

~ % str="hello bash"
 ~ % echo $str
hello bash

变量的引用

变量的引用
 \${变量}称作对变量的引用
 echo \${变量名}查看变量的值
 \${变量名}在部分情况下可以省略为 $变量名
(1)当需要在变量后面加内容时,需要使用echo ${变量名}

~ % str="hello bash"
 ~ % echo $str
hello bash
 ~ % str="hello bash"
 ~ % echo $str
hello bash
 ~ % echo ${str}
hello bash
# 当需要在变量后面加内容时,需要使用echo ${变量名}
 ~ % echo $str123
 ~ % echo ${str}123
hello bash123

变量的作用范围

变量的默认作用范围
变量的导出
 export
变量的删除
 unset

(1)子进程无法访问父进程的变量

# 在父进程定义了变量a
 ~ % a=1
# 进入一个子进程,访问父进程的变量a,访问不到
 ~ % bash
The default interactive shell is now zsh.
To update your account to use zsh, please run `chsh -s /bin/zsh`.
For more details, please visit https://support.apple.com/kb/HT208050.
bash-3.2$ echo $a
bash-3.2$ a=2
bash-3.2$ exit
exit
# 在父进程访问变量a,访问的是父进程定义的,非子进程定义的
 ~ % echo $a
1

(2)变量的导出

# 在父进程定义了变量a
 ~ % a=1
# 定义一个可执行文件,内容如下:
 test % ls -l aa.sh
-rwxr--r--  1 user1  staff  20  4  4 18:44 aa.sh
 test % cat aa.sh
#!/bin/bash
echo $a
# 在子进程中执行aa.sh,发现获取不到变量值
 test % bash aa.sh

 test % ./aa.sh

# 在父进程中执行,能够拿到变量值
 test % source aa.sh
1
 test % . ./aa.sh
1
# 使用export将变量导出,子进程就能获取到变量值
 test % export a
 test % bash aa.sh  
1

相关推荐