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"

     看下结果:

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

  • 5
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值