linux shell中./a.sh , sh a.sh , source a.sh, . ./a.sh的区别

版权声明:本文为博主原创文章,转载时请务必注明本文地址, 禁止用于任何商业用途, 否则会用法律维权。 https://blog.csdn.net/stpeace/article/details/83035218

      在linux shell中, 执行shell script的方式有多种, 有什么区别呢?  实际上我之前说过, 现在用一个简单例子再来说下。

      a.sh的内容是:

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

       看下结果:

ubuntu@VM-0-15-ubuntu:~$ echo $$
21657
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ 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
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ ./a.sh 
hello world
PID of this script: 28875
PPID of this script: 21657
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ sh ./a.sh 
hello world
PID of this script: 28895
PPID of this script: 21657
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ sh a.sh 
hello world
PID of this script: 28908
PPID of this script: 21657
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ source ./a.sh 
hello world
PID of this script: 21657
PPID of this script: 21656
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ source a.sh   
hello world
PID of this script: 21657
PPID of this script: 21656
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ 
ubuntu@VM-0-15-ubuntu:~$ . ./a.sh
hello world
PID of this script: 21657
PPID of this script: 21656
ubuntu@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 directory
ubuntu@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生效

猜你喜欢

转载自blog.csdn.net/stpeace/article/details/83035218
.sh
SH