«

linux执行shell脚本的方式及一些区别

时间:2016-3-28 08:27     作者:admin     分类: Linux


假设shell脚本文件为hello.sh
放在/root目录下。下面介绍几种在终端执行shell脚本的方法:

[root@localhost home]# cd /root/

[root@localhost ~]#vim hello.sh

#!  /bin/bash

cd /tmp

echo "hello guys!"

echo "welcome to my Blog:linuxboy.org!"

 

1.切换到shell脚本所在的目录,执行:

[root@localhost ~]# ./hello.sh

-bash: ./ hello.sh权限不够

 

2.以绝对路径的方式执行:

[root@localhost ~]# /root/Desktop/hello.sh

-bash: /root/Desktop/ hello.sh: 权限不够

 

3.直接用bashsh执行:

[root@localhost ~]# bash hello.sh

hello guys!

welcome to my Blog:linuxboy.org!

[root@localhost ~]# pwd

/root

 

[root@localhost ~]# sh hello.sh

hello guys!

welcome to my Blog:linuxboy.org!

[root@localhost ~]# pwd

/root

注意:用以上三种方法执行shell脚本,现行的shell会开启一个子shell环境,去执行shell脚本,前两种必须要有执行权限才能够执行

 

也可以让shell脚本在现行的shell中执行:

4.现行的shell中执行

[root@localhost ~]# . hello.sh

hello guys!

welcome to my Blog:linuxboy.org!

[root@localhost tmp]# pwd

/tmp

 

 

[root@localhost ~]# source hello.sh

hello guys!

welcome to my Blog:linuxboy.org!

[root@localhost tmp]# pwd

/tmp

 

对于第4种不会创建子进程,而是在父进程中直接执行

上面的差异是因为子进程不能改变父进程的执行环境,所以CD(内建命令,只有内建命令才可以改变shell 的执行环境)没有成功,但是第4种没有子进程,所以CD成功

本文出处:http://4554480.blog.51cto.com/4544480/837006

标签: 代码 shell 分享 Linux 运维

版权所有:Mrxn's Blog
文章标题:linux执行shell脚本的方式及一些区别
除非注明,文章均为 Mrxn's Blog 原创,请勿用于任何商业用途,转载请注明作者和出处 Mrxn's Blog

扫描二维码,在手机上阅读

推荐阅读: