字符串測試

字符串測試

    ==:表示測試兩個字符串是否相等,相等爲真,否則爲假

    !=:表示測試兩字符串是否不等

    >:字符串比較大小

    <:字符串比較大小

    單目運算    

    -n string:測試字符串是否爲空,空爲真,否則爲假 

    -z string:測試指定字符串是否不爲空,空爲假,否則爲真

實例

    1、寫一腳本,通過參數傳遞用戶名,判斷用戶名是否和基本組名一致,如一致顯示ok,否則not same;

    [root@station01 ~]# cat test14.sh 
    #!/bin/bash
    #
    if ! id  $1 &>/dev/null;then
            echo "No such user."
            exit 12
    fi
    if [ $1 == `id -n -g $1` ];then
            echo "Ok"
    else
            echo "Not same."
    fi

    2、寫一個腳本,通過參數傳遞,判斷輸入的如是q,Q,quit,Quit或QUIT退出腳本,否則顯示參數

    [root@station01 ~]# cat test15.sh 
    #!/bin/bash
    #
    if [ $# -lt 1 ];then
            echo "Argument is less than 1."
            exit 1
    fi
    #
    if [ $1 = 'q' ];then
            echo "Quiting...."
            exit 2
    elif [ $1 = 'Q' ];then
            echo "Quiting...."
            exit 3
    elif [ $1 = 'quit' ];then
            echo "Quiting...."
            exit 4
    elif [ $1 = 'Quit' ];then
            echo "Quiting...."
            exit 5
    elif [ $1 = 'QUIT' ];then
            echo "Quiting...."
            exit 6
    else 
            echo $1
    fi

    3、bc命令的學習

    1)方法1

    [root@station01 ~]# echo "scale=2;33/12;" |bc
    2.75

    2)方法2

    [root@station01 ~]# bc <<<"scale=2;33/12;"
    2.75

    4、傳遞三個參數,第一個爲整數,第二個爲算術運算符,第三個爲整數,將計算結果顯示出來,並保留兩位精度

    [root@station01 ~]# cat test16.sh 
    #!/bin/bash
    #
    if [ $# -lt 3 ];then
            echo "Argument:$0 ARG1 ARG2 ARG3"
            exit 2
    fi
    echo "scale=2;$1$2$3;" | bc


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章