作者:stpeace(作者為CSDN資深7年專家)
https://blog.csdn.net/stpeace/article/details/83035218
在linux shell中, 執行shell script的方式有多種, 有什么區別呢? 實際上我之前說過, 現在用一個簡單例子再來說下。
a.sh的內容是:
#! /bin/bashecho hello worldecho "PID of this script: $$"echo "PPID of this script: $PPID"
看下結果:
ubuntu@VM-0-15-ubuntu:~$ echo $$21657ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ a.shNo command 'a.sh' found, did you mean:Command 'ash' from package 'ash' (universe)Command 'adsh' from package 'apt-dater' (universe)a.sh: command not foundubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ ./a.shhello worldPID of this script: 28875PPID of this script: 21657ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ sh ./a.shhello worldPID of this script: 28895PPID of this script: 21657ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ sh a.shhello worldPID of this script: 28908PPID of this script: 21657ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ source ./a.shhello worldPID of this script: 21657PPID of this script: 21656ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ source a.shhello worldPID of this script: 21657PPID of this script: 21656ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ . ./a.shhello worldPID of this script: 21657PPID of this script: 21656ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ ../a.sh-bash: ../a.sh: No such file or directoryubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$ubuntu@VM-0-15-ubuntu:~$
一步一步地來說:
當前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生效