• Bash 语法笔记


    ## 一个简单的示例
    新建一个文件,`test.sh`,输入以下代码:

    ```
    #!/bin/bash
    echo "hello, $USER. I wish to list some files of yours"
    echo "listing files in the current directory, $PWD"
    ls # 列出当前目录所有文件
    ```
    这个简单的示例说明几点内容:

    1. `#!/bin/bash` 表示bash文件的开头
    2. `echo` 语句
    3. `ls` 语句
    4. `#`表示注释

    ## 变量

    ```
    #!/bin/bash
    X=""
    if [ -n $X ]; then # -n 用来检查变量是否非空
    echo "the variable X is not the empty string"
    fi
    ```
    这个示例说明几点内容:

    1. `#!/bin/bash` 表示bash文件的开头
    2. `X=""`变量的定义方式
    3. `if` 语句
    4. `$X` 变量的引用方式

    > 注意: 单引号和双引号的区别,变量名会在双引号中展开,单引号中则不会。
    ```
    #!/bin/bash
    echo -n '$USER=' # -n选项表示阻止echo换行
    echo "$USER"
    echo "$USER=$USER" # 该命令等价于上面的两行命令
    ```
    > 注意: 大括号保护变量
    ```
    #!/bin/bash
    X=ABC
    echo "${X}abc"
    ```

    ## 条件语句, if/then/elif
    语法:
    ```
    if condition
    then
    statement1
    statement2
    ..........
    else
    statement3
    fi
    ```

    示例:
    ```
    #!/bin/bash
    X=3
    Y=4
    empty_string=""
    if [ $X -lt $Y ] # is $X less than $Y ?
    then
    echo "$X=${X}, which is smaller than $Y=${Y}"
    fi

    if [ -n "$empty_string" ]; then
    echo "empty string is non_empty"
    fi

    if [ -e "${HOME}/.fvwmrc" ]; then # test to see if ~/.fvwmrc exists
    echo "you have a .fvwmrc file"
    if [ -L "${HOME}/.fvwmrc" ]; then # is it a symlink ?
    echo "it's a symbolic link
    elif [ -f "${HOME}/.fvwmrc" ]; then # is it a regular file ?
    echo "it's a regular file"
    fi
    else
    echo "you have no .fvwmrc file"
    fi
    ```

    ## 循环

    ### for
    ```
    #!/bin/bash
    for X in red green blue
    do
    echo $X
    done
    ```
    ### while
    ```
    #!/bin/bash
    X=0
    while [ $X -le 20 ]
    do
    echo $X
    X=$((X+1))
    done
    ```

  • 相关阅读:
    智能实验室-结构化存储浏览器(SSExplorer) 1.5.0.150
    智能实验室-杀马(Defendio) 3.1.0.681
    智能实验室-结构化存储浏览器(SSExplorer) 1.6.0.160
    IT餐馆—第八回 三十
    使用Silverlight Toolkit 绘制图表区域图和冒泡图
    IT餐馆—第十二回 软培
    IT餐馆—第四回 离职
    IT餐馆—第一回 前言
    IT餐馆—第十回 潜伏
    IT餐馆—第十三回 重构
  • 原文地址:https://www.cnblogs.com/lonicera/p/8018595.html
Copyright © 2020-2023  润新知