zoukankan      html  css  js  c++  java
  • 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
    ```

  • 相关阅读:
    网络流24题-分配问题
    网络流24题-圆桌问题
    git ssh
    SQL Server 添加说明 语句
    问题思路
    数据库事务和锁
    Castle Windsor
    Flask学习笔记11之特殊的装饰器
    python中的"环绕通知"
    Flask学习笔记10之flash
  • 原文地址:https://www.cnblogs.com/lonicera/p/8018595.html
Copyright © 2011-2022 走看看