Linux中bash編程,Linuxbash編程

來源:互聯網
上載者:User

Linux中bash編程,Linuxbash編程

bash編程也叫shell編程

  

預定義變數
        $? 最後一次執行的命令的返回狀態。如果這個變數的值為0,證明上一個命令正確的執行;如果這個變數返回的值非0(具體是那個數,有命令自己來決定),則證明上一個命令執行不正確。
        $$當前進程的進程號(PID)
        $!後台啟動並執行最後一個進程的進程號(PID)
  運算子
        declare 聲名變數的類型  
        declare [+/-][選項] 變數名
        - 給變數設定類型屬性
        + 取消變數的類型屬性
        -i 將變數聲名為整數型
        -x將變數什申明為環境變數
        -p 顯示指定變數的被聲名的類型

舉例:

a=1b=2declare -i c = $a+$bc=$(($a+$b))

注意用雙小括弧,因為Linux中認為一切皆為字元。

如果不加()當成一個命令,shell指令碼中Linux命令在 $() 中運行,當然可以直接寫命令,如果則一些引用命令時 就要 $()


單分支if  條件陳述式
if [ 條件判斷式 ];then    程式fior  if [ 條件判斷式 ]    then        程式fi
判斷登入使用者是否為root使用者:
#!/bin/bash#grep 擷取行萬用字元#cut 擷取列統配符,以 = 分割 2 擷取第二列login_name=$(env | grep LOGNAME | cut -d "=" -f 2)#echo $login_nameif [ "$login_name" != "root" ]        then                echo 'isnot root'fi
判斷根分區的佔用率
#!/bin/bash#df -h 任性話顯示磁碟的利用率#awk 擷取第五列#cut 對字元用 % 進行分割 擷取第一列值result=$( df -h | grep sda1 | awk '{print  $5}'  | cut -d % -f 1)if [ "$result" -lt '90' ]        then                echo 'the root dir  is not full'fi
雙分支if條件陳述式
if [ 條件判斷式 ]    then         ...    else        ...fi
判斷nginx 是否在運行 (最好不用包含nginx作為檔案名稱)
#!/bin/bashresult=$(ps aux | grep nginx | grep -v grep)if [ -n "$result" ]        then                echo "$(date) nginx is ok !"        else                echo "$(date) nginx is not ok !"                sudo /etc/init.d/nginx start &>/dev/null                echo "$(date) restart nginx !!"fi
多分支if語句
if []    then elif []    then...else    ...if

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.