zoukankan      html  css  js  c++  java
  • shell

    例一:if的三种写法

    #!/bin/sh
    message="Hello"
    
    if test "$message" = "Hello"; then
        echo "hello world"
    fi
    
    if [ "$message" = "Hello" ]; then
            echo "hello world"
    fi
    
    if [[ $message == "Hello" ]];then
            echo "Hello world3"
    fi

     sh是软连接bash,#!/bin/bash也可。

    注意:【<条件式>】和【【<条件式>】】

    <条件式>和这边的括号之间,==、=与左边的变量、右边的字符串之间都要有空格

    变量是双引号里面,不是单引号。

    例二:while循环

    #!/bin/bash
    
    first=$1
    step=$2
    last=$3
    
    c=$first
    
    while [[ $c -le $last ]];do
            echo $c
            c=$(( c + step ))
    done

     例三、变量与连接字符串

    #!/bin/sh
    
    set -x
    message="hello"
    read name
    set +x
    echo "$message ,$name"
    echo "${message}world"

    例四:根据返回值来判断。或赋予一个变量

    #!/bin/bash
    
    if grep "hello" /home/shell/hello1.sh >/dev/null 2>&1; then
            echo "Hello world1"
    fi
    
    grep "hello" /home/shell/hello1.sh >/dev/null 2>&1
    rc=$?
    if [[ $rc -eq 0 ]]; then
            echo "hello world2"
    fi

    例五:$() 和$(())

    #!/bin/sh
    message="sh命令行的路径是$( which sh)"
    echo $message

    输出结果为:sh命令行的路径是/bin/sh

    $()把命令行里面的取出来,当成变量来使用。

    $(()) 也同理,不过最里面的括号不需要给变量附加$。如例二。

    附录:if中的条件式如下:

    1 字符串判断

    str1 = str2      当两个串有相同内容、长度时为真 
    str1 != str2      当串str1和str2不等时为真 
    -n str1        当串的长度大于0时为真(串非空) 
    -z str1        当串的长度为0时为真(空串) 
    str1           当串str1为非空时为真

    2 数字的判断

    int1 -eq int2    两数相等为真 
    int1 -ne int2    两数不等为真 
    int1 -gt int2    int1大于int2为真 
    int1 -ge int2    int1大于等于int2为真 
    int1 -lt int2    int1小于int2为真 
    int1 -le int2    int1小于等于int2为真

    3 文件的判断

    -r file     用户可读为真 
    -w file     用户可写为真 
    -x file     用户可执行为真 
    -f file     文件为正规文件为真 
    -d file     文件为目录为真 
    -c file     文件为字符特殊文件为真 
    -b file     文件为块特殊文件为真 
    -s file     文件大小非0时为真 
    -t file     当文件描述符(默认为1)指定的设备为终端时为真

    3 复杂逻辑判断

    -a         与 
    -o        或 
    !        非

  • 相关阅读:
    互联网协议入门(二)
    互联网协议入门(一)
    careercup-扩展性和存储限制10.6
    careercup-扩展性和存储限制10.4
    careercup-扩展性和存储限制10.3
    写一个函数找到给定字符串的位置
    手工删除crfclust.bdb文件
    VirtualBox 报错VERR_VD_IMAGE_READ_ONLY
    Oracle DG测试failover和后续恢复报告
    ASM的备份集在文件系统上恢复测试
  • 原文地址:https://www.cnblogs.com/bluewelkin/p/4386750.html
Copyright © 2011-2022 走看看