shell腳本編寫

shell腳本編寫

shell語法

summary

  1. 編寫shell腳本時(shí),需要聲明這是一個(gè)腳本文件#!/bin/bash

  2. 聲明作者,和編寫日期。

  3. NOTE: 盡可能詳細(xì)的寫出腳本的功能,做好注釋。shell的可讀性不是很好,因此強(qiáng)烈建議編寫注釋。

Hello World

#!/bin/bash
# this is a annotation
# auto echo hello world!
# by authors nulijiushimeili 2015
echo "hello world!"
echo -e "\033[32mPlease select Menu follow:\033[0m"
echo "1)installing apache server."
echo "2)installing mysql server."
echo "3)installing php server."
echo "4)deploying lamp web goals."
echo -e "\033[32m-----------------------------------------\033[0m"

獲得執(zhí)行的結(jié)果信息

  1. 當(dāng)狀態(tài)碼等于0時(shí)表示執(zhí)行成功,否則表示命令執(zhí)行失敗
#!/bin/bash
# 測(cè)試一條命令的執(zhí)行結(jié)果
# 2019-02-19

service iptables stop

# 第一種寫法,-eq 表示 =
if [ $? -eq 0 ]; then
    echo "success!"
else
    echo "failed!"
fi

# 第二種寫法,-ne 表示 !=
if [ $? -ne 0 ]; then
    echo "failed!"
else
    echo "success!"
fi

  1. 將命令執(zhí)行的結(jié)果返回給一個(gè)變量。
#!/bin/bash
# 得到執(zhí)行命令的結(jié)果

res=`ps -ef | grep mysql-server`
echo $res

變量的使用

#!/bin/bash
# define path variables
name="Tom"
echo "$name"
echo "This is my name $name."
# shell process id.
echo $UID
# shell home
echo $PWD
echo "#######################"
# the first paramiter
echo $0
# the second paramiter
echo $1 $2
echo "#########################"
# expresses shell running ok
echo "The \$? is $?"
# get all parameters
echo "The \$* is $*"
# return how much params 
echo "The \$# is $#"

if 語句

#!/bin/bash
# auto if test
# by author nulijiushimeili 2015

num1=$1
num2=$2
if (($#<2));then
    echo "Usage: if.sh param1 param2."
    echo "wrong input !!!"
else 
    if(($num1>$num2));then
        echo "This $num1 greate $num2 !"
    elif(($num1<$num2));then
        echo "This $num1 little $num2 !"
    else
        echo "The $num1 equals $num2 !"
    fi
fi

# check and mkdir
dir=temp
if [ ! -d $dir ];then
        mkdir -p $dir
        echo "create dir $dir success!"
else
        echo "$dir is exists."
fi


elseif 語句

#!/bin/bash
# if else test demo
# by author nulijiushimeili

scores=$1
if (($#>0));then
    if [[$scores -gt 85]];then
        echo "Very good!";
    elif [[$scores -gt 70]];then
        echo "good";
    elif [[$scores -gt 60]];then
        echo "pass";
    else 
        echo "so bad!";
    fi
else
    echo "Usage: elif.sh param1";
fi

for語句

#!/bin/bash
# test for
# by author nulijiushimeili 2015

# first test
for i in {1..5}
do
    echo $i
done

# second test
for i in 6 7 8 9 10
do
    echo $i
done

# third test
for FILE in $HOME/*
do
    echo $FILE
done

# high order usage
for((i=0;i<10;i++))
do
    echo $i
done


while 語句

#!/bin/bash
# test while loop
# by author nulijiushimeili

# print number from 1 to 5
counter=0
while [ $counter -lt 5 ]
do
    counter=`expr $counter + 1`
    echo $counter
done

# print input number in while loop 
echo "please input a number."
echo "ctrl + d to exit."
while read FILM
do
    echo "Yeah! great film the $FILM"
done


case語句

#!/bin/bash
# test case
# by author nulijiushimeili 2015

#if(($#>0))
if [ $# -gt 0 ]
then
    case $1 in
    1)
        echo "one"
        ;;
    2)
        echo "two"
        ;;
    3)
        echo "three"
        ;;
    4)
        echo "four"
        ;;
    *)
        echo -e "\033[32mNothing to matched.\033[0m"
        ;;  
    esac
else
    echo "Must to input a number parameter."
    echo "please input a number in {1,2,3,4}."
    echo "Usage: case.sh 1"
fi


shell函數(shù)

#!/bin/bash
# test function
# by author nulijiushimeili

# 聲明一個(gè)方法
print(){
    echo "hello word."
}

# 調(diào)用方法
print

test(){
    num1=3
    num2=4
    return $(($num1 + $num2))
}

test
result=$?
echo $result

按行讀取文件

#!/bin/base
# read file and get each line
# by author nulijiushimeili 2017

# -r express : allow special charactor
while read -r line
do
    echo $line
done </opt/datas/emp.txt


# test add 
i=1
sum=0
while ((i<10))
do
    sum=$((sum=i+$sum))
    i=$[i+1]
done
echo $sum

shell 編程知識(shí)

輸出帶顏色的打印信息

# 輸出帶顏色的打印信息
echo -e "\033[32m------\033[0m"
# 輸出黑底白字的信息
echo -e "\033[40,37m------\033[0m"

字體顏色設(shè)置

# 字體顏色設(shè)置
echo -e “\033[30m 黑色字 \033[0m”
echo -e “\033[31m 紅色字 \033[0m”
echo -e “\033[32m 綠色字 \033[0m”
echo -e “\033[33m 黃色字 \033[0m”
echo -e “\033[34m 藍(lán)色字 \033[0m”
echo -e “\033[35m 紫色字 \033[0m”
echo -e “\033[36m 天藍(lán)字 \033[0m”
echo -e “\033[37m 白色字 \033[0m”

字體底色設(shè)置

# 字體底色設(shè)置
echo -e “\033[40;37m 黑底白字 \033[0m”
echo -e “\033[41;37m 紅底白字 \033[0m”
echo -e “\033[42;37m 綠底白字 \033[0m”
echo -e “\033[43;37m 黃底白字 \033[0m”
echo -e “\033[44;37m 藍(lán)底白字 \033[0m”
echo -e “\033[45;37m 紫底白字 \033[0m”
echo -e “\033[46;37m 天藍(lán)底白字 \033[0m”
echo -e “\033[47;30m 白底黑字 \033[0m”

特殊參數(shù)

# 參數(shù)
$# 參數(shù)的個(gè)數(shù)
$? shell 腳本運(yùn)行返回值,OK返回0
$* 所有的參數(shù)

$UID 用戶id,root的uid=0
$PWD 當(dāng)前文件夾絕對(duì)路徑

邏輯運(yùn)算符解析

# 邏輯運(yùn)算符解析
-f  判斷文件是否存在
-d  判斷目錄是否存在
-eq 等于,應(yīng)用于整型數(shù)值比較
-ne 不等于,應(yīng)用于整型數(shù)值比較
-lt 小于,應(yīng)用于整型數(shù)值比較
-gt 大于,應(yīng)用于整型數(shù)值比較
-le 小于或等于,應(yīng)用于整型數(shù)值比較
-ge 大于或等于,應(yīng)用于整型數(shù)值比較
-a  雙方都成立(and)  condition1 -a condition2
-o  單方成立(or) condition1 -o condition2
-z  空字符串

測(cè)試腳本編寫是否正確

/bin/bash -n if.sh      # 如果沒有輸出任何東西表示腳本編寫正確

文件IO

# 將結(jié)果寫入文件,結(jié)果不會(huì)在控制臺(tái)展示,而是在文件中,覆蓋寫
$ echo result > file
# 將結(jié)果寫入文件,結(jié)果不會(huì)在控制臺(tái)展示,而是在文件中,追加寫
$ echo result >> file
echo input < file  #獲取輸入流

一些練習(xí)的小例子

  1. 自動(dòng)備份mysql數(shù)據(jù)庫

    #!/bin/bash
    # auto backup mysql db
    # by author nulijiushimeili 2015
    # define backup path
    
    bak_dir=/opt/datas/mysql_backup/`date +%Y%m%d`
    mysql_db=sqoop
    mysql_user=root
    mysql_pwd=123456
    mysql_cmd=/usr/bin/mysqldump
    
    if [ $UID -ne 0 ]
    then
     echo "Must to be use root for exec shell."
     exit
    fi
    
    if [ ! -d $bak_dir ]
    then
     mkdir -p $bak_dir
     echo -e "\033[32mThe $bak_dir create successfully!\033[0m"
    else
     echo "This $bak_dir is exists ..."
    fi
    
    # mysql backup cmd.
    mysqldump -u$mysql_user -p$mysql_pwd -d $mysql_db >$bak_dir/$mysql_db.sh
    
    if [ $? -eq 0 ]
    then
     echo -e "\033[32mThe mysql backup $mysql_db successfully!\033[0m" 
    else
     echo -e "\033[32mThe mysql backup $mysql_db failed, please check.\033[0m"
    fi
    
    
    1. 玩具程序: 設(shè)置環(huán)境變量(第一版)

      #!/bin/bash
      # set env
      # by author nulijiushimeili 2017
      
      time=`date +%Y%m%d%H%M%S`
      new_profile="profile_$time"
      
      echo $new_profile
      
      if [ $UID -ne 0 ]
      then
        echo "Must to be use root to exec shell."
        exit
      fi
      
      if [ $1 == "help" ]
            then
                echo "Usage: set-env.sh JAVE_HOME."
                echo "Usage: set-env.sh help for help."
                exit
      fi
      
      echo "Are you sure to append this dir to envirement virable?"
      echo "input y to continue and copy /etc/profile to $new_profile, the new file will as a backup for /etc/profile, if you want to use the old profile, you can rename the histry profile to 'profile'."
      echo "continue to input 'y', and input 'n' for exit.[y|n]?"
      read create_file_yes_or_no
      if [ $create_file_yes_or_no == "y" ] 
      then
        sudo cp /etc/profile /etc/$new_profile
        if [ $? -eq 0 ]
        then
            echo "create new profile success."
            if [ $# -gt 0 ]
            then
                # content=echo "# $1%nexport $1=$PWD%nexport PATH=\$PATH=\$PATH:\$$1/bin"
                sh="export PATH=\$PATH:\$$1/bin"
                home="export $1=$PWD"
                annotation="# $1"
                echo "append env variable to profile..."
                echo "the variable is :"
                echo "$annotation"
                echo "$home"
                echo "$sh"
                echo "It is appending now,please comfirm agagin:"
                echo "continue to input 'y', and input 'n' for exit.[y|n]?"
                read get_yes_or_no
                if [ $get_yes_or_no == "y" ]
                then
                    sudo sed -i "4i\ \n" /etc/profile
                    sudo sed -i "4i\\$sh" /etc/profile
                    sudo sed -i "4i\\$home" /etc/profile
                    sudo sed -i "4i\\$annotation" /etc/profile
                    sudo source /etc/profile
                    echo "$1 envirement virable was setted successfully!"
                    echo "$1"
                else
                    echo "exit!"
                    exit
                fi
            else
                echo "Usage: set-env.sh JAVE_HOME."
                echo "Usage: set-env.sh help for help."
                exit
            fi
        else
            echo "create new profile failed. please to check ..."
        fi
      else
        echo "exit!"
        exit
      fi
      
      
  3. 玩具程序: 設(shè)置環(huán)境變量(第二版)

  ```shell
  #!/bin/babin
  # set env
  # by author nulijiubinimeili 2017
  
  time=`date +%Y%m%d%H%M%S`
  new_profile="profile_$time"
  
  
  echo "will create new profile $new_profile for backup."
  
  # check user, must be root
  if [ $UID -ne 0 ]
  then
    echo "Must to be use root to exec shell."
    exit
  fi
  
  # help info
  if [ $1 == "help" ]
        then
            echo "Usage: set-env.bin JAVE_HOME.(requer: this binell must in the java home directory.)"
            echo "Usage: set-env.bin /opt/modules/jdk1.8.0_161 JAVE_HOME"
            echo "Usage: set-env.bin help"
            exit
  fi
  
  echo "Appending this dir to envirement virable."
  echo "input y to continue and copy /etc/profile to $new_profile, the new file will as a backup for /etc/profile, if you want to use the old profile, you can rename the histry profile to 'profile'."
  echo "continue to input 'y', and input 'n' for exit.[y|n]?"
  read create_file_yes_or_no
  if [ $create_file_yes_or_no == "y" ] 
  then
    sudo cp /etc/profile /etc/$new_profile
    if [ $? -eq 0 ]
    then
        echo "create new profile success."
        if [ $# -eq 1 ]
        then
            # Must contains a bin directory in current path.
            if [ ! -d $PWD/bin ]
            then
                    echo -e "\033[32mWithout 'bin' directory in current path,pleash check.\033[0m"
                    exit
            fi
            # content=echo "# $1%nexport $1=$PWD%nexport PATH=\$PATH:\$$1/bin"
            echo "Recommend: set-env.x.x.x.sh /path XXX_HOME"
            bin="export PATH=\$PATH:\$$1/bin"
            home="export $1=$PWD"
            annotation="# $1"
            echo "append env variable to profile..."
            echo "the variable is :"
            echo -e "\033[32m$annotation\033[0m"
            echo -e "\033[32m$home\033[0m"
            echo -e "\033[32m$bin\033[0m"
            echo "It is appending now,please comfirm agagin:"
            echo "continue to input 'y', and input 'n' for exit.[y|n]?"
            read get_yes_or_no
            if [ $get_yes_or_no == "y" ]
            then
                sudo sed -i "4i\ \n" /etc/profile
                sudo sed -i "4i\\$bin" /etc/profile
                sudo sed -i "4i\\$home" /etc/profile
                sudo sed -i "4i\\$annotation" /etc/profile
                source /etc/profile
                echo "$1 envirement virable was setted successfully!"
                echo -e "\033[32mplease exec 'source /etc/profile' by yourself.\033[0m"
            else
                echo "exit!"
                exit
            fi
        elif [ $# == 2 ]
        then
            # content=echo "# $2%nexport $2=$PWD%nexport PATH=\$PATH:\$$2/bin"
            bin="export PATH=\$PATH:\$$2/bin"
            home="export $2=$1"
            annotation="# $2"
            echo "append env variable to profile..."
            echo "the variable is :"
            echo -e "\033[32m$annotation\033[0m"
            echo -e "\033[32m$home\033[0m"
            echo -e "\033[32m$bin\033[0m"
            echo "It is appending now,please comfirm agagin:"
            echo "continue to input 'y', and input 'n' for exit.[y|n]?"
            read get_yes_or_no
            if [ $get_yes_or_no == "y" ]
            then
                sudo sed -i "4i\\$bin" /etc/profile
                sudo sed -i "4i\\$home" /etc/profile
                sudo sed -i "4i\\$annotation" /etc/profile
                sudo sed -i "4i\ \n" /etc/profile
                source /etc/profile
                echo "$1 envirement virable was setted successfully!"
                echo -e "\033[32mplease exec 'source /etc/profile' by yourself.\033[0m"
            else
                echo "exit!"
                exit
            fi
        else
            echo "Usage: set-env.bin JAVE_HOME.(requer: this binell must in the java home directory.)"
            echo "Usage: set-env.bin /opt/modules/jdk1.8.0_161 JAVE_HOME"
            echo "Usage: set-env.bin help"
            exit
        fi
    else
        echo "create new profile failed. please to check ..."
    fi
  else
    echo "exit!"
    exit
  fi
  
  
  ```

  4. git 提交

  ```shell
  #!/bin/bash
  # git commit project
  # by author nulijiushimeili
  
  echo "start running shell"
  git add .
  if (($#>0));
  then
    git commit -m $1
  else
    echo "Usage: gitcommit.sh param1"
  fi
  git push orgin master
  
  if (($?==0))
  then
    echo "commit success."
  else
    echo "commit failed, please try to again."
  fi
  ```

  5. 啟動(dòng)Tomcat

  ```shell
  #!/bin/bash
  # 啟動(dòng)Tomcat
  tomPath=/usr/local/soft/tom7
  # sh ${tomPath}/bin/shutdown.sh
  # 作為參數(shù)返回 查找的進(jìn)程ID 
  id=`ps -ef |grep tomcat |grep -v 'auto tomcat'|awk '{print $2}'`
  kill -9 $id
  rm -rf /usr/local/soft/tom7/webapps/ROOT*
  cp  /home/grq/data/ROOT.war /usr/local/soft/tom7/webapps/
  sh ${tomPath}/bin/startup.sh
  
  
  # 作為參數(shù)返回 查找的進(jìn)程ID 
  id=$(ps -ef |grep tomcat |grep -v 'auto tomcat'|awk '{print $2}')
  
  ```
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容