美文网首页
十三 Shell篇——变量赋值、引用、作用范围

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

作者: supermanto | 来源:发表于2020-04-04 18:51 被阅读0次

    变量的定义

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

    变量的赋值

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

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

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

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

    user1@SC02ZRC4KMD6N ~ % str="hello bash"
    user1@SC02ZRC4KMD6N ~ % echo $str
    hello bash
    

    变量的引用

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

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

    变量的作用范围

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

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

    # 在父进程定义了变量a
    user1@SC02ZRC4KMD6N ~ % a=1
    # 进入一个子进程,访问父进程的变量a,访问不到
    user1@SC02ZRC4KMD6N ~ % 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,访问的是父进程定义的,非子进程定义的
    user1@SC02ZRC4KMD6N ~ % echo $a
    1
    

    (2)变量的导出

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

    相关文章

      网友评论

          本文标题:十三 Shell篇——变量赋值、引用、作用范围

          本文链接:https://www.haomeiwen.com/subject/yusjphtx.html