linux執行shell腳本的方式及一些區別

假設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.直接用bash或sh執行:

[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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章