欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

shell腳本內調用另外一個shell腳本的幾種方法講解

 更新時間:2023年06月26日 15:52:10   作者:fengbingchun  
在Linux開發(fā)中經常會編寫shell腳本來執(zhí)行一些任務,下面這篇文章主要給大家介紹了關于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ù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論