轻松读懂 Bash Shell 脚本

作者: 清醒的cola | 来源:发表于2016-12-20 23:22 被阅读460次

    开始

    • touch script.sh 创建一个第一个脚本 script.sh (# 为注解)
    #!/bin/bash  # 脚本的第一行叫 shebang,用来告知系统如何执行该脚本
    echo Hello, world!
    
    • 添加可执行权限 chmod a+x script.sh
    • 执行脚本 sh script.sh

    注意事项

    echo 'the first line'; echo 'the second line'  # 每一句指令以换行或分号隔开
    echo 'the first line' && echo 'the second line'  # 以 && 隔开,first 成功才执行 second
    echo 'the first line' || echo 'the second line'  # 以 || 隔开,first 失败才执行 second
    echo "There are $(ls | wc -l) items here." # 一个指令可用 $( ) 嵌套在另一个指令内部
    

    变量

    # 声明变量
    VARIABLE="Some string" #  每个变量的值都是字符串形式。
    VARIABLE = "Some string" #  注意空格 Bash 会把 VARIABLE 当做一个指令,由于找不到该指令,因此这里会报错。
    
    # 使用变量
    echo $VARIABLE  # 如果要使用变量的值, 则要加 $。
    echo "$VARIABLE"
    echo '$VARIABLE'  # 注意: ' (单引号) 不会展开变量(即会屏蔽掉变量)。
    
    # 内置变量
    echo "上个进程退出状态,成功退出,状态为0,否则,非0: $?"
    echo "脚本的 PID: $$"
    echo "参数数目: $#"
    echo "脚本所有参数: $@"
    echo "不同位置参数: $1 $2..."
    

    环境变量env

    • PATH 查找可执行文件路径 在/etc/environment 或 /ect/profile 或 ~/.bashrc
    • HOME home 目录
    • PWD 当前目录
    • USER 当前用户
    • UID root的UID=0
    • SHELL 当前shell版本
    • export PATH=$PATH:/new/path/ 设置环境变量 export 当前shell程序都会继承这个变量

    逻辑控制

    if

    #!/bin/bash
    echo "What's your name?"
    read NAME # 这里不需要声明新变量
    echo Hello, $NAME!
    
    if [[ $Name == $USER ]]
    then
        echo "Your name is you username"
    else
        echo "Your name isn't you username"
    fi
    

    for

    # 注意 ` ` 和 $( ) 等价。seq 返回长度为 3 的数组。
    for VARIABLE in `seq 3`
    do
        echo "$VARIABLE"
    done
    

    while

    while [ true ]
    do
        echo "loop body here..."
        break
    done
    

    表达式

    echo $(( 10 + 5 ))

    函数

    function foo ()
    {
        echo "Arguments work just like script arguments: $@"
        echo "And: $1 $2..."
        echo "This is a function"
        return 0
    }
    

    foo "My name is" $NAME # 调用函数

    试着读一读

    #!/bin/bash
    dir=${PWD}
    bfinder=`echo $PATH|grep $dir`
    echo $bfinder
    if [ "$bfinder" == "" ]
    then
        echo "export PATH=/$PATH:${dir}" >> ~/.bash_profile
        export PATH=$PATH:${dir}
    fi
    

    答案:将当前文件地址作为默认路径写入环境变量

    雾霾天 等风来

    相关文章

      网友评论

        本文标题:轻松读懂 Bash Shell 脚本

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