• shell结构化命令


    • if-then

    if command

    then

        commands

    fi

    一个例子:

    只要if后面的命令运行完成后,退出状态码正常,即为0,then部分的命令就会执行。

    • if-then-else

    if command

    then

        commands

    else

        commands

    fi

    • 嵌套if

    if command1

    then

        commands

    elif command2

    then

        more commands

    fi

    • test命令

    test测试条件是否成立,成立test返回状态码0,不成立,返回错误状态码。

    if test condition

    then

        commands

    fi

    或者

    if [ condition ]  #括号间要有空格

    then

        commands

    fi

    test可以判断3类条件:

    数值比较:

    n1 -eq n2 是否相等

    n1 -ge n2 n1是否大于或等于n2

    n1 -gt n2  n1 是否大于n2

    n1 -le n2  n1是否小鱼货等于n2

    n1 -lt n2   n1是否小于n2

    n1 -ne n2  n1是否不等于n2

    bash shell仅能处理整数。bash计算器将浮点值作为字符串值存储进一个变量。

    字符串比较

    str1 = str2  是否相同

    str1 != str2 是否不同

    str1 < str2   1是否比2小

    str1 > str2   1 是否比2大

    -n str1    str1的长度是否非0

    -z str1     str1的长度是否为0   对于不存在的变量,是按空变量来处理的

    > 和 <号需要用转移符

    对于大写字母和小写字母的比较 test跟sort顺序是不一样的,sort是大写大,test是小写大

    文件比较

    -d file 检查file是否存在并是一个目录

    -e file 检查file是否存在

    -f file 检查file是否存在病史一个文件

    -r file 检查file是否存在并可读

    -s file 检查file是否存在并非空

    -w file 检查file是否存在并可写

    -x file 检查file是否存在并可执行

    -O file 检测file是否存在并属当前用户所有

    -G file 检测fiile是否存在并且默认组与当前用户相同

    file1 -nt file2 检测file1是否比file2新

    file1 -ot file2 检测file1是否比file2旧

    • 复合条件测试

    &&  逻辑与

    ||     逻辑或

    • if-then的高级特性

    双小括号 

    双方括号  针对字符串

     

    • case

    跟 c语言的 switch类似

    • for命令

    for var in list

    do

        commands

    done

    •  while

    while test command

    do

        other commands

    done

    while可以指定多个值,只有最后一个测试命令的状态码会被while采用

    • until

    until test commands

    do

        other commands

    done

    until也可以有多个测试命令,但是只有最后一个命令的退出状态码会被while采用

    • 嵌套循环

    for循环嵌套for循环的例子:

    • 循环处理文件数据

    处理/etc/passwd文件

    • 控制循环

    break命令退出循环

    跳出外部循环 break n 你说明跳出循环的层级,默认n为1,跳出当前循环。设置n为2的话就会停止下一级的外部循环。

    continue命令,只是跳出挡圈循环

    continue n 中 n定义要继续的循环层级

    • 处理循环输出

    done后面  > test.txt  输出从定向

    done后面 | sort  输出结果排序

  • 相关阅读:
    Codeforces Round #719 (Div. 3) 题解
    Codeforces Global Round 14 A~F题解
    AtCoder Beginner Contest 199 题解
    Codeforces Round #716 (Div. 2) A~D 题解
    Codeforces Round #713 (Div. 3) 题解
    Codeforces Round #712 (Div. 2) A~E 题解
    CodeCraft-21 and Codeforces Round #711 (Div. 2) A~E 题解
    CF839 D 莫比乌斯反演
    java存大数和高精度浮点数(BigInteger与BigDecimal)
    java科学计算常用方法(Math)
  • 原文地址:https://www.cnblogs.com/laiyuan/p/7171649.html
Copyright © 2020-2023  润新知