更新時間:2022-10-26 10:13:52 來源:動力節點 瀏覽1658次
相信大家對shell腳本語言工作原理已經有所了解,那么,shell腳本執行的方式有哪些?動力節點小編來告訴大家。
Linux中shell腳本的執行通常有4種方式,分別為工作目錄執行,絕對路徑執行,sh執行,shell環境執行。
首先,看下我們的腳本內容
[tan@tan scripts]$ ll
total 4
-rw-rw-r--. 1 tan tan 68 May 8 23:18 test.sh
[tan@tan scripts]$ cat test.sh
#!/usr/bin/bash
/usr/bin/python <<-EOF
print "Hello Shell"
EOF
工作目錄執行,指的是執行腳本時,先進入到腳本所在的目錄(此時,稱為工作目錄),然后使用 ./腳本方式執行
[tan@tan scripts]$ ./test.sh
-bash: ./test.sh: Permission denied
[tan@tan scripts]$ chmod 764 test.sh
[tan@tan scripts]$ ./test.sh
Hello Shell
這里需要賦權,使用chmod 764 test.sh 賦權后就可以正常執行了
./的意思是說在當前的工作目錄下執行hello.sh。如果不加上./,bash可能會響應找到不到hello.sh的錯誤信息。因為目前的工作目錄 (/data/shell)可能不在執行程序默認的搜索路徑之列,也就是說,不在環境變量PASH的內容之中。查看PATH的內容可用 echo $PASH 命令。現在的/data/shell就不在環境變量PASH中的,所以必須加上./才可執行。
絕對路徑中執行,指的是直接從根目錄/到腳本目錄的絕對路徑
[tan@tan scripts]$ pwd
/home/tan/scripts
[tan@tan scripts]$ `pwd`/test.sh
Hello Shell
[tan@tan scripts]$ /home/tan/scripts/test.sh
Hello Shell
這里 `pwd` 指的是該命令執行結果,等同于 /home/tan/scripts
sh執行,指的是用腳本對應的sh或bash來接著腳本執行
[tan@tan scripts]$ sh test.sh
Hello Shell
[tan@tan scripts]$ bash test.sh
Hello Shell
注意,若是以方法三的方式來執行,那么,可以不必事先設定shell的執行權限,甚至都不用寫shell文件中的第一行(指定bash路徑)。因為方法三 是將hello.sh作為參數傳給sh(bash)命令來執行的。這時不是hello.sh自己來執行,而是被人家調用執行,所以不要執行權限。
shell環境執行,指的是在當前的shell環境中執行,可以使用 . 接腳本 或 source 接腳本
[tan@tan scripts]$ . test.sh
Hello Shell
[tan@tan scripts]$ source test.sh
Hello Shell
以上就是關于“4種shell腳本執行的方式”介紹,大就如果對此比較感興趣,想了解更多相關知識,不妨來關注一下本站的Linux教程,里面還有更豐富的知識等著大家去學習,希望對大家能夠有所幫助。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習