1. 程式人生 > >linux shell中./a.sh , sh a.sh , source ./a.sh, . ./a.sh的區別

linux shell中./a.sh , sh a.sh , source ./a.sh, . ./a.sh的區別

      在linux shell中, 執行shell script的方式有多種, 有什麼區別呢?  實際上我之前說過, 現在用一個簡單例子再來說下。

      a.sh的內容是:

#! /bin/bash
echo hello world
echo "PID of this script: $$"
echo "PPID of this script: $PPID"

       看下結果:

[email protected]:~$ echo $$
21657
[email protected]:~$ 
[email protected]:~$ 
[email protected]
:~$ [email protected]:~$ a.sh No command 'a.sh' found, did you mean: Command 'ash' from package 'ash' (universe) Command 'adsh' from package 'apt-dater' (universe) a.sh: command not found [email protected]:~$ [email protected]:~$ [email protected]:~$ [email protected]:~$ ./a.sh hello world PID of this script: 28875 PPID of this script: 21657
[email protected]
:~$ [email protected]:~$ [email protected]:~$ [email protected]:~$ sh ./a.sh hello world PID of this script: 28895 PPID of this script: 21657 [email protected]:~$ [email protected]:~$ [email protected]:~$ [email protected]:~$ sh a.sh hello world PID of this script: 28908 PPID of this script: 21657
[email protected]
:~$ [email protected]:~$ [email protected]:~$ [email protected]:~$ source ./a.sh hello world PID of this script: 21657 PPID of this script: 21656 [email protected]:~$ [email protected]:~$ [email protected]:~$ [email protected]:~$ source a.sh hello world PID of this script: 21657 PPID of this script: 21656 [email protected]:~$ [email protected]:~$ [email protected]:~$ [email protected]:~$ . ./a.sh hello world PID of this script: 21657 PPID of this script: 21656 [email protected]:~$ [email protected]:~$ [email protected]:~$ [email protected]:~$ ../a.sh -bash: ../a.sh: No such file or directory [email protected]:~$ [email protected]:~$ [email protected]:~$ [email protected]:~$

         一步一步地來說:

        當前shell程序的程序號是21657

        用a.sh來執行是萬萬要不得的, 少了./

        ./a.sh,sh ./a.sh和sh a.sh是一樣的, 實際上是啟了一個子shell來執行a.sh, 所以可以看到PPID of this script: 21657

        source ./a.sh ,source a.sh 和. ./a.sh是一樣的, 都是在當前shell中執行指令碼, 請看程序號

        ../a.sh是萬萬要不得的,兩個點之間沒有空格

       最後要說明的兩點是:

      1. 用sh和source去執行時, 不要求a.sh有可執行許可權, 但單獨./a.sh這樣去搞時,需要可執行許可權

      2. 大家在開發專案時,經常需要設定環境變數, 當然是用source啊, 確保在當前shell生效