Linux shell中./a.sh , sh a.sh , source a.sh, . ./a.sh的区别(写的非常棒!还有实例~)

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生效

你可能感兴趣的:(Linux,linux,shell)