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


 

1   ./需要执行权限,使用脚本文件中第一行#!指定的shell(解释器)来执行命令(譬如常见的/bin/bash),不指定系统会调用默认shell程序

2   sh不需要执行权限,是使用sh这个shell执行命令,是个软链接,它可能是一个任意的shell,通常默认是bash shel,用type命令可以查看

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

慕城南风

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值