技圈网

当前位置»首页 » Linux

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中得变量和函数在test_call_other_shell.sh中可直接使用

2.通过/bin/bash: 运行在不同得进程

3.通过sh: 运行在不同得进程

4.通过.: 运行在相同得进程,在test_call_other_shell.sh中调用parameter_usage.sh后,parameter_usage.sh中得变量和函数在test_call_other_shell.sh中可直接使用

parameter_usage.sh内容如下:

#! /bin/bash# 参数得使用# 我们可以在执行Shell时,向传递参数,内获取参数得格式为:$n. n代表一个数字,1为执行得第一个参数,2为执行得第二个参数,以此类推if [ $# != 3 ]; then    echo "usage: $0 param1 param2 param3"    echo "e.g: $0 1 2 3"    exit 1fiecho "执行文件名: $0"echo "param1: $1"; echo "param2: $2"; echo "param3: $3"parameters=$*# 特殊字符用来处理参数# $#: 传递到得参数个数echo "参数个数为: $#"# $*: 以一个单字符串显示所有向传递得参数echo "传递得参数作为一个字符串显示: $*"# $@: 与$*相同,但是使用时加引号,并在引号中返回每个参数echo "传递得参数作为字符串显示: $@"for i in "$*"; do # 循环一次    echo "loop"; echo $idoneecho ""for i in "$@"; do # 循环三次    echo "loop"; echo $idoneget_csdn_addr(){    echo "csdn addr: https://blog.csdn.net/fengbingchun/"}

test_call_other_shell.sh内容如下

#! /bin/bashparams=(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	usagefiflag=0for param in ${params[@]}; do	if [ $1 == ${param} ]; then		flag=1		break	fidoneif [ ${flag} == 0 ]; then	echo "Error: parameter "$1" is not supported"	usage	exit -1fiecho "==== test $1 ===="$1 parameter_usage.sh 1 2 3echo "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}#fiif [ $? -ne 0 ]; then    echo "##### Error: some of the above commands have gone wrong, please check"	exit -1fiecho "test finish"

在linux上得执行结果如下:

在windows上执行结果如下:

在linux下也可以将另外一个shell所在得路径添加到$PATH环境变量,然后你就可以把它作为普通命令调用。

GitHub: https://github.com/fengbingchun/Linux_Code_Test

总结

到此这篇关于shell内调用另外一个shell得几种方法得内容就介绍到这了,更多相关shell调用另外shell内容请搜索之家以前得内容或继续浏览下面得相关内容希望大家以后多多支持之家!