初識shell指令碼

何少俠發表於2018-08-13

1.1 指令碼認識

  •  1 #!/bin/bash 

第一行,通常用來指定執行指令碼的shell ,/bin/bash是CentOS 預設的shell  如果寫到第二行,就是註釋了

  •  1 #!/bin/sh 

這樣寫也是可以的,sh是bash的軟連結,和#!/bin/bash 是沒有區別的,理規範的開頭使用#!/bin/bash

1.2 檢視bash版本

  •  1 [root@oldboy-lesson scripts]# bash --version
     2 GNU bash, version 4.1.2(2)-release (x86_64-redhat-linux-gnu)
     3 Copyright (C) 2009 Free Software Foundation, Inc.
     4 License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
     5  
     6 This is free software; you are free to change and redistribute it.
     7 There is NO WARRANTY, to the extent permitted by law.
     8 [root@oldboy-lesson scripts]# cat test_1.sh
     9 #!/bin/bash
    10 user=`whoami`
    11 echo $user
    12 [root@oldboy-lesson scripts]# sh test_1.sh
    13 root
    14 [root@oldboy-lesson scripts]# ./test_1.sh
    15 root
    16 [root@oldboy-lesson scripts]# . test_1.sh
    17 root
    18 [root@oldboy-lesson scripts]# source test_1.sh
    19 root
    20 [root@oldboy-lesson scripts]# /bin/bash test_1.sh
    21 root
    22 [root@oldboy-lesson scripts]# /bin/sh test_1.sh
    23 root
    24 [root@oldboy-lesson scripts]# /server/scripts/test_1.sh
    25 root

     

1.3 書寫指令碼

 

1.3.1 執行指令碼

 

1.3.1.1  小結:

執行指令碼的方法有:sh       ./          .           source /bin/bash         /bin/sh pwd/

1.4 繼承指令碼變數

  •  1 [root@oldboy-lesson scripts]# sh test_1.sh
     2 root
     3 [root@oldboy-lesson scripts]# echo $user
     4  
     5 [root@oldboy-lesson scripts]# ./test_1.sh
     6 root
     7 [root@oldboy-lesson scripts]# echo $user
     8  
     9 [root@oldboy-lesson scripts]# bash test_1.sh
    10 root
    11 [root@oldboy-lesson scripts]# echo $user
    12  
    13 [root@oldboy-lesson scripts]# . test_1.sh
    14 root
    15 [root@oldboy-lesson scripts]# echo $user
    16 root
    17 [root@oldboy-lesson scripts]# source test_1.sh
    18 root
    19 [root@oldboy-lesson scripts]# echo $user
    20 root

1.4.1.1  小結

繼承:source 和 .      能繼承指令碼的變數,其它命令皆不能繼承

相關文章