shell概述

前言

什麼是shell

  • 保護內核的一個殼
  • 腳本中命令的解釋器
  • 把命令翻譯成系統能識別的語言

shell腳本的意義

  • 記錄命令執行的過程和執行邏輯,以便以後重複執行
  • 腳本可以批量處理主機
  • 腳本可以定時處理主機

如何創建shell腳本

#!/bin/bash (#!幻數,這一行在腳本運行的最開始,會先把/bin/bash環境開啓,預示頂級程序)
linux還有可能是:sh bash csh tsh
unix下:kcsh sh

vim自動添加腳本首部

vim /etc/vimrc
"map <F4> ms:call WESTOSTITLE()<cr>'s
autocmd BufNewFile *.sh,*.script call WESTOSTITLE()
func WESTOSTITLE()
 call append(0,"###############################################")
 call append(1,"# Author: lee")
 call append(2,"# Version: ")
 call append(3,"# Create_Time: ".strftime("%Y/%m/%d"))
 call append(4,"# Mail: [email protected]")
 call append(5,"# Info: ")
 call append(6,"# ")
 call append(7,"################################################")
 call append(8,"")
 call append(9,"#!/bin/bash")
endfunc	

如何執行shell腳本

面試或者筆試會被問道

  • 手動在環境中開啓指定解釋器
    sh script.sh

      [root@rhel7_node1 mnt]# sh westos.sh 
      
      [1]+  Stopped                 sh westos.sh
      [root@rhel7_node1 mnt]# ps f
         PID TTY      STAT   TIME COMMAND
       47558 pts/3    Ss+    0:00 bash
       40303 pts/1    Ss+    0:00 bash
        9520 pts/0    Ss     0:04 bash
       58424 pts/0    T      0:00  \_ sh westos.sh (在當前環境中開啓了新的shell)
       58425 pts/0    T      0:00  |   \_ watch -n 1 date
       58436 pts/0    R+     0:00  \_ ps f
        8134 tty1     Ssl+  10:04 /usr/bin/X :0 -background none -noreset -audit 4 -verbo
    

    tcsh script.sh

      [root@rhel7_node1 mnt]# tcsh westos.sh 
    
      [1]+  Stopped                 tcsh westos.sh
      [root@rhel7_node1 mnt]# ps f
         PID TTY      STAT   TIME COMMAND
       47558 pts/3    Ss+    0:00 bash
       40303 pts/1    Ss+    0:01 bash
        9520 pts/0    Ss     0:04 bash
       59793 pts/0    T      0:00  \_ tcsh westos.sh
       59800 pts/0    T      0:00  |   \_ watch -n 1 date
       59811 pts/0    R+     0:00  \_ ps f
        8134 tty1     Ssl+  10:35 /usr/bin/X :0 -background none -noreset -audit 4 -verbo
    
  • 直接在當前環境中運行shell中的指令不開啓新的shell
    source script.sh
    . script.sh(效果同source)

      [root@rhel7_node1 mnt]# source westos.sh 
      
      [1]+  Stopped                 watch -n 1 date
      [root@rhel7_node1 mnt]# ps f
         PID TTY      STAT   TIME COMMAND
       47558 pts/3    Ss+    0:00 bash
       40303 pts/1    Ss+    0:00 bash
        9520 pts/0    Ss     0:04 bash
       58470 pts/0    T      0:00  \_ watch -n 1 date(在當前shell中執行)
       58481 pts/0    R+     0:00  \_ ps f
        8134 tty1     Ssl+  10:05 /usr/bin/X :0 -background none -noreset -audit 4 -verbo
    
  • 開啓腳本中指定的shell並使用此shell環境運行腳本中的指令
    chmod +x script.sh
    /xxx/xxx/script.sh
    ./script.sh

如何對腳本進行調試

運行指令:sh -x /mnt/westos.sh
+(運行指令)
不帶+ (命令運行的輸出)

腳本練習:
1.ip_show.sh 網卡 顯示當前的主機名稱
2.host_messages.sh 顯示當前主機的名稱,ip,登陸當前主機的用戶
hostname: xxxxx
ipaddress: xxxx.xxxx.xxx.xxx
username: root
3.clear_log.sh 執行一次腳本後可以清空日誌

後記

理解and練習

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