shell指令碼的執行方式

2021-10-09 19:43:22 字數 1799 閱讀 5368

linux中shell指令碼的執行通常有4種方式,分別為工作目錄執行,絕對路徑執行,sh執行,shell環境執行。

首先,看下我們的指令碼內容

[plum@plum scripts]$ ll

total 4

-rw-rw-r--. 1 plum plum 68 may 8 23:18 test.sh

[plum@plum scripts]$ cat test.sh

#!/usr/bin/bash

/usr/bin/python <<-eof

print "hello shell"

eof

1、工作目錄執行

工作目錄執行,指的是執行指令碼時,先進入到指令碼所在的目錄(此時,稱為工作目錄),然後使用 ./指令碼方式執行

[plum@plum scripts]$ ./test.sh

-bash: ./test.sh: permission denied

[plum@plum scripts]$ chmod 764 test.sh

[plum@plum scripts]$ ./test.sh

hello shell

./的意思是說在當前的工作目錄下執行hello.sh。如果不加上./,bash可能會響應找到不到hello.sh的錯誤資訊。因為目前的工作目錄 (/data/shell)可能不在執行程式預設的搜尋路徑之列,也就是說,不在環境變數pash的內容之中。檢視path的內容可用 echo $pash 命令。現在的/data/shell就不在環境變數pash中的,所以必須加上./才可執行。

2、絕對路徑執行

絕對路徑中執行,指的是直接從根目錄/到指令碼目錄的絕對路徑

plum@plum scripts]$ pwd

/home/plum/scripts

[plum@plum scripts]$ `

pwd`

/test.sh

hello shell

[plum@plum scripts]$ /home/plum/scripts/test.sh

hello shell

這裡pwd指的是該命令執行結果,等同於 /home/plum/scripts

3、sh執行

sh執行,指的是用指令碼對應的sh或bash來接著指令碼執行

[plum@plum scripts]$ sh test.sh 

hello shell

[plum@plum scripts]$ bash test.sh

hello shell

注意,若是以方法三的方式來執行,那麼,可以不必事先設定shell的執行許可權,甚至都不用寫shell檔案中的第一行(指定bash路徑)。

因為方法三 是將hello.sh作為引數傳給sh(bash)命令來執行的。這時不是hello.sh自己來執行,而是被人家呼叫執行,所以不要執行許可權。那麼不用 指定bash路徑自然也好理解了啊

4、shell環境執行

shell環境執行,指的是在當前的shell環境中執行,可以使用 . 接指令碼 或 source 接指令碼

[plum@plum scripts]$ . test.sh 

hello shell

[plum@plum scripts]$ source test.sh

hello shell

shell指令碼執行方式

echo輸出命令 echo 選項 輸出內容 選項 e 支援反斜線控制的字元轉換 shell指令碼 指令碼都以.sh結束,指令碼第一行 bin bash 以hello.sh簡單指令碼為例 指令碼執行有兩種方法 這裡出現了no such file or directory 原因是格式不匹配,解決方案 d...

shell 指令碼的執行方式

執行shell指令碼的方式基本上有三種 1 輸入定向到shell指令碼 這種方式是用輸入重定向方式讓shell從給定檔案中讀入命令列並進行相應處理。其一般形式是 bash 指令碼名 例如 bash 2 以指令碼名作為引數 其一般形式是 bash 指令碼名 引數 例如 bash ex2 usr men...

執行Shell指令碼的方式

執行shell指令碼的方式基本上有三種 1 輸入定向到shell指令碼 這種方式是用輸入重定向方式讓shell從給定檔案中讀入命令列並進行相應處理。其一般形式是 bash 指令碼名 例如 bash shell從檔案ex1中讀取命令列,並執行它們。當shell到達檔案末尾時就終止執行,並把控制返回到s...