Shell的條件表達式介紹

判斷b.txt這個文件是否存在,存在輸出1,不存在輸出0

[ -f b.txt ]&& echo 1||echo 0

-f:判斷是否爲文件

-e:判斷文件是否存在

-d:判斷是否爲目錄

-r:判斷是否可讀

-w:判斷是否可寫

-x:判斷是否可執行


對單個文件或目錄變量的測試需要加雙引號,避免錯誤

file=/etc/services
[ -f "$file" ]&& echo 1||echo 0

條件表達式判斷條件後面執行多條命令語句寫法

#!/bin/bash
[ $1 -eq 2 ]&&{
echo "true"
}||{
echo "false"
}
# &&成立後執行後面的語句; ||不成立就執行後面的語句
#如果輸入的值等於2就打印true
#否則打印false
#sh test.sh 2:打印true


常用字符串測試操作符:

-z "字符串"字符串長度爲0則爲真
-n "字符串"字符串長度不爲0則爲真
"串1" = "串2"串1等於串2則爲真
"串1" != "串2"串1不等於串2則爲真

PS:

①、以上表格中的字符串測試操作符號務必要用""引起來

②、比較符號的兩端必須有空格

#字符串長度爲0所以輸出1
[ -n "" ]&& echo 1||echo 0


整數表達式:

blob.png

blob.png


Shell特殊變量:Shell $0, $#, $*, $@, $?, $$和命令行參數


特殊變量列表
變量含義
$0當前腳本的文件名
$n傳遞給腳本或函數的參數。n 是一個數字,表示第幾個參數。例如,第一個參數是$1,第二個參數是$2。
$#傳遞給腳本或函數的參數個數。
$*傳遞給腳本或函數的所有參數。
$@傳遞給腳本或函數的所有參數。被雙引號(" ")包含時,與 $* 稍有不同,下面將會講到。
$?上個命令的退出狀態,或函數的返回值。
$$當前Shell進程ID。對於 Shell 腳本,就是這些腳本所在的進程ID。

命令行參數

運行腳本時傳遞給腳本的參數稱爲命令行參數。命令行參數用 $n 表示,例如,$1 表示第一個參數,$2 表示第二個參數,依次類推。



邏輯連接符:

blob.png

blob.png


比較兩個整數的大小案例:

第一種方法:

#!/bin/bash
read -p "please input two num:" num1 num2
a=$num1
b=$num2
#判斷鍵入值是否爲空
[ -z "$a" -o -z "$b" ]&&{
        echo "USAGE: num1 num2"
        exit 1
}
#a變量如果不是整數則打印echo
[ "`echo "$a"|sed -r 's#[^0-9]##g'`" = "$a" ]||{
        echo "first arg must be int."
        exit 2
}
#b變量如果不是整數則打印echo
[ "`echo "$b"|sed -r 's#[^0-9]##g'`" = "$b" ]||{
        echo "second arg must be int."
        exit 2
}
#判斷a與b的大小關係
[ $a -lt $b ]&&{
        echo "$a<$b"
        exit 0
}
[ $a -eq $b ]&&{
        echo "$a=$bA"
        exit 0
}
[ $a -gt $b ]&&{
        echo "$a>$b"
        exit 0
}

第二種方法:

#!/bin/bash
#鍵入值必須爲2個
[ $# -ne 2 ]&&{
        echo "USAGE: num1 num2"
        exit 1
}
#a變量如果不是整數則打印echo
[ "`echo "$1"|sed -r 's#[^0-9]##g'`" = "$1" ]||{
        echo "first arg must be int."
        exit 2
}
#b變量如果不是整數則打印echo
[ "`echo "$2"|sed -r 's#[^0-9]##g'`" = "$2" ]||{
        echo "second arg must be int."
        exit 2
}
#判斷a與b的大小關係
[ $1 -lt $2 ]&&{
        echo "$1<$2"
        exit 0
}
[ $1 -eq $2 ]&&{
        echo "$1=$2"
        exit 0
}
[ $1 -gt $2 ]&&{
        echo "$1>$2"
        exit 0
}


一二級菜單操作案例:

#!/bin/bash
file=/test/3.sh
menu(){
cat <<END
1.[install lamp]
2.[install lnmp]
3.[exit]
please input one number:
END
}
menu
read num1
a=$num1
#判斷腳本是否存在
[ -e $file ]||{
        echo "$file is not!"
}
#判斷腳本是否可執行
[ -x $file ]||{
        echo "$file not execute!"
        exit 0
}
#用戶鍵入1,執行腳本,並打印腳本執行語句
[ $a -eq 1 ]&&{
        echo "start installing lamp"
        sh $file
        echo "lamp is installed!"
        exit 1
}
[ $a -eq 2 ]&&{
        echo "start installing lnmp"
        sh $file
        echo "lnmp is installed"
        exit 2
}
[ $a -eq 3 ]&&{
        exit 3
}
echo "Input error!"
exit 0


if條件語句

單分支結構語法:

if[ 條件 ]
    then
        指令
fi

或

if [ 條件 ];then
    指令
fi

雙分支結構語法:

if[ 條件 ]
    then
        指令1
else
        指令2
fi

多分支結構語法:

if 條件1
    then
        指令1
elif 條件2
    then
        指令2
else
        指令3
fi


shell腳本之特殊變量

$0       腳本的名稱
$1,$2,$3....   第一個參數,第二個參數,第三個參數
$?  上一次執行的狀態碼 
$#  參數個數 
$*  參數列表 
$@  參數列表


shell的數值運算方法

expr、(())、let、bc、$[]、awk、typeset

常用就(())、let這兩種

#加減乘除
[root@test test]# echo 4+6|bc
10
[root@test test]# echo 4*6|bc
24
[root@test test]# echo 4/6|bc
0
[root@test test]# echo 4-6|bc
-2

#10進制轉2進制或16進制
[root@test test]# echo "obase=2;6"|bc
110
[root@test test]# echo "obase=16;60"|bc
3C

#awk數值運算
[root@test test]# echo 60 2|awk '{print $1-$2}'
58
[root@test test]# echo 60 2|awk '{print $1*$2}'
120
[root@test test]# echo 60 2|awk '{print $1/$2}'
30
[root@test test]# echo 60 2|awk '{print $1+$2}'
62

[root@test test]# echo "`seq -s "+" 10`="$((`seq -s "+" 10`))
1+2+3+4+5+6+7+8+9+10=55

[root@test ~]# echo `seq -s '+' "10"`=`seq -s "+" "10"|bc`
1+2+3+4+5+6+7+8+9+10=55

[root@test ~]# echo `echo {1..5}|tr " " "+"`=`echo {1..5}|tr " " "+"|bc`
1+2+3+4+5=15


變量的讀入之read

read -p "please input three number:" num1 num2 num3

例子:

#!/bin/sh
read -p "please input two number:" num1 num2
a=$num1
b=$num2
#判斷鍵入值是否爲空
if [ -z $a ]
then
        echo "please input a!"
        exit 1
fi
if [ -z $b ]
then
        echo "please input b!"
        exit 1
fi
#判斷鍵入值是否爲數字
expr $a + $b + 1 &>/dev/null
if [ $? -ne 0 ]
then
        echo "is not int!"
        exit 2
fi
#no.3
echo "$a-$b =$[a-b]"
echo "$a+$b =$[a+b]"
echo "$a*$b =$[a*b]"
if [ $b -eq 0 ]
then
        echo "b is not zero!"
else
        echo "$a/$b =$[a/b]"
fi
echo "$a**$b =$[a**b]"
if [ $b -eq 0 ]
then
        echo "b is not zero!"
else
        echo "$a%$b =$[a%b]"
fi


給字符串設定顏色:

#!/bin/sh
#顏色
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
RES='\E[0m'
#報錯信息反饋
usage(){
        echo "USAGE:$0 red|green|yellow|blue word"
}
#設定字體顏色
color(){
        if [ "$1" = "red" ];then
                echo -e "${RED_COLOR}$2 $RES"
        elif [ "$1" = "green" ];then
                echo -e "${GREEN_COLOR}$2 $RES"
        elif [ "$1" = "yellow" ];then
                echo -e "${YELLOW_COLOR}$2 $RES"
        elif [ "$1" = "blue" ];then
                echo -e "${BLUE_COLOR}$2 $RES"
        else
                usage
        fi
}
#主函數
main(){
        if [ $# -ne 2 ];then
                usage
        else
        color $1 $2
        fi
}
main $*


執行腳本打印水果菜單並加上不同的顏色以及介紹:

#!/bin/sh
#顏色
RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
RES='\E[0m'
#菜單
menu(){
cat <<END
1.apple
2.pear
3.banana
4.cherry
END
read -p "please input one number:" num1
}
menu
a=$num1
case "$a" in
        1)
        echo -e "this is ${RED_COLOR}蘋果 $RES"
;;
        2)
        echo -e "this is ${GREEN_COLOR}梨子 $RES"
;;
        3)
        echo -e "this is ${YELLOW_COLOR}香蕉 $RES"
;;
        4)
        echo -e "this is ${BLUE_COLOR}櫻桃 $RES"
;;
        *)
        echo "please input 1~4 number!"
        exit 0
esac


Nginx啓動腳本並實現加入開機自啓動管理

#!/bin/sh
[ -f /etc/init.d/functions ]&& . /etc/init.d/functions
nginx_pid=/usr/local/nginx/logs/nginx.pid
nginx=/usr/local/nginx/sbin/nginx
#start_nginx
start_nginx(){
        if [ -f $nginx_pid ];then
                action "Nginx is started!" /bin/false
        else
                $nginx &>/dev/null
                action "Nginx is start!" /bin/true
        fi
}
#stop_nginx
stop_nginx(){
        if [ -f $nginx_pid ];then
                $nginx -s stop &>/dev/null
                action "Nginx is stop!!" /bin/true
        else
                action "Nginx is stoped!" /bin/false
        fi
}
#reload_nginx
reload_nginx(){
        if [ -f $nginx_pid ];then
                $nginx -s reload &>/dev/null
                action "Nginx is reloaded!" /bin/true
        else
                action "Can't open $nginx_pid, no such this file" /bin/false

        fi
}
quit(){
        exit 0
}
case "$1" in
        start)
        start_nginx
;;
        stop)
        stop_nginx
;;
        restart)
        stop_nginx
        sleep 2
        start_nginx
;;
        reload)
        reload_nginx
;;
        *)
        echo "USAGE:$0 start|stop|reload"
        quit
esac

添加到開機自啓動步驟:

1、cp startNginx.sh /etc/rc.d/init.d/startNginx

2、chmod +x startNginx

3、vim startNginx

#添加以下兩行
# chkconfig: 2345 56 60
# Description: this is a http server.

    2345:是指系統運行級別,分別爲rc.2、rc.3、rc.4、rc.5 

    56:啓動的優先級【不能使用被佔用的序號】

    blob.png

    60:關閉的優先級【不能使用被佔用的序號】

    blob.png

    PS:如果啓動優先級配置的數太小時如0時,則有可能啓動不成功,因爲此時可能其依賴的網絡服務還沒有啓動,從而導致自啓動失敗。

4、chkconfig --add startNginx

5、chkconfig startNginx on

6、chkconfig --list|grep startNginx【如果nginxStart存在,則添加成功】

就可以使用service startNginx start|stop|restart|reload


shell腳本手機充值例子:

#!/bin/sh
sum=1000
i=500
method(){
read -p "please input msg:" TXT
read -p "send msg,are you sure?[y|n]" select
case "$select" in
  y)
    ((sum=sum-i))
    echo "send $TXT is ok!"
    echo "you have $sum money!"

  ;;
  n)
    echo "you select can't send msg!"
    echo "you have $sum money!"
    exit 1
  ;;
  *)
  echo "USAGE: please input [y|n]!"
  exit 2
esac
}
#判斷是否爲int
judge(){
    expr $1 + 1 &>/dev/null
    #這裏有個小問題,如果充值負數也可以...知道的,請賜教...謝謝
    if [ $? -ne 0 -a "$1" != "-1" ];then
        echo "INVALID INPUT!"
        exit 8
    else
        return 0
    fi
}
while true
do
  if  [ $sum -ge $i ];then
        method
  else
        read -p "您的餘額不足,是否需要充值?[y|n]" select2
        case "$select2" in
          y)
             read -p "How much do you want to recharge[INT]:" add
             judge $add
             ((sum=sum+${add}))
             echo "pay successful! The balance is ${sum} !"
             read -p "Whether to continue texting?[y|n]" msg
                case "$msg" in
                    y)
                        while [ $sum -ge $i ]
                        do
                        method
                        done
                        continue
                    ;;
                    n)
                        echo "即將退出!感謝使用!"
                        exit 6
                    ;;
                    *)
                        echo "USAGE:您的輸入有誤!"
                        exit 5
                esac
          ;;
          n)
             echo "you only $sum money!Can't send msg!"
             exit 3
         ;;
          *)
             echo "USAGE: without the select!"
             exit 4
        esac
  break
  fi
done


while循環小結:

blob.png



shell腳本調試方法:

blob.png







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