shell腳本內調用另外一個shell腳本的幾種方法講解
有時會在一個shell腳本(如test_call_other_shell.sh)中調用另外一個shell腳本(如parameter_usage.sh),這里總結幾種可行的方法,這些方法在linux上和windows上(通過Git Bash)均適用:
1.通過source: 運行在相同的進程,在test_call_other_shell.sh中調用parameter_usage.sh后,parameter_usage.sh中的變量和函數(shù)在test_call_other_shell.sh中可直接使用
2.通過/bin/bash: 運行在不同的進程
3.通過sh: 運行在不同的進程
4.通過.: 運行在相同的進程,在test_call_other_shell.sh中調用parameter_usage.sh后,parameter_usage.sh中的變量和函數(shù)在test_call_other_shell.sh中可直接使用
parameter_usage.sh內容如下:
#! /bin/bash # 參數(shù)的使用 # 我們可以在執(zhí)行Shell腳本時,向腳本傳遞參數(shù),腳本內獲取參數(shù)的格式為:$n. n代表一個數(shù)字,1為執(zhí)行腳本的第一個參數(shù),2為執(zhí)行腳本的第二個參數(shù),以此類推 if [ $# != 3 ]; then echo "usage: $0 param1 param2 param3" echo "e.g: $0 1 2 3" exit 1 fi echo "執(zhí)行文件名: $0" echo "param1: $1"; echo "param2: $2"; echo "param3: $3" parameters=$* # 特殊字符用來處理參數(shù) # $#: 傳遞到腳本的參數(shù)個數(shù) echo "參數(shù)個數(shù)為: $#" # $*: 以一個單字符串顯示所有向腳本傳遞的參數(shù) echo "傳遞的參數(shù)作為一個字符串顯示: $*" # $@: 與$*相同,但是使用時加引號,并在引號中返回每個參數(shù) echo "傳遞的參數(shù)作為字符串顯示: $@" for i in "$*"; do # 循環(huán)一次 echo "loop"; echo $i done echo "" for i in "$@"; do # 循環(huán)三次 echo "loop"; echo $i done get_csdn_addr() { echo "csdn addr: https://blog.csdn.net/fengbingchun/" }
test_call_other_shell.sh內容如下:
#! /bin/bash params=(source /bin/bash sh .) usage() { echo "Error: $0 needs to have an input parameter" echo "supported input parameters:" for param in ${params[@]}; do echo " $0 ${param}" done exit -1 } if [ $# != 1 ]; then usage fi flag=0 for param in ${params[@]}; do if [ $1 == ${param} ]; then flag=1 break fi done if [ ${flag} == 0 ]; then echo "Error: parameter \"$1\" is not supported" usage exit -1 fi echo "==== test $1 ====" $1 parameter_usage.sh 1 2 3 echo "parameters: ${parameters}" get_csdn_addr $1 parameter_usage 123 #ret=$? #if [[ ${ret} != 0 ]]; then # echo "##### Error: some of the above commands have gone wrong, please check: ${ret}" # exit ${ret} #fi if [ $? -ne 0 ]; then echo "##### Error: some of the above commands have gone wrong, please check" exit -1 fi echo "test finish"
在linux上的執(zhí)行結果如下:
在windows上執(zhí)行結果如下:
在linux下也可以將另外一個shell腳本所在的路徑添加到$PATH環(huán)境變量,然后你就可以把它作為普通命令調用。
GitHub: https://github.com/fengbingchun/Linux_Code_Test
總結
到此這篇關于shell腳本內調用另外一個shell腳本的幾種方法的文章就介紹到這了,更多相關shell腳本調用另外shell腳本內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
linux 驅動之Kconfig文件和Makefile文件實例
這篇文章主要介紹了linux 驅動之Kconfig文件和Makefile文件實例的相關資料,需要的朋友可以參考下2017-01-01Linux Bash 提示符的一些騷操作(自定義 Bash 提示符)
這篇文章主要介紹了Linux Bash 提示符的一些騷操作,一些能讓你自定義 Bash 提示符的黑科技,需要的朋友可以參考下2017-07-07bash?shell?自定義函數(shù)命令持久化生效問題
這篇文章主要介紹了bash?shell?自定義函數(shù)命令持久化生效,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03Linux中使用expect腳本實現(xiàn)遠程機器自動登錄
本篇文章給大家介紹在Linux中使用expect腳本實現(xiàn)遠程機器自動登錄,前提是要創(chuàng)建一個expec腳本ssh_expect,接下來定義一些命令別名等,下面跟著腳本之家小編一起學習學習吧2015-09-09