shell脚本内调用另外一个shell脚本的几种方法

文章介绍了如何在shell脚本中调用另一个shell脚本的四种方法,包括使用source、/bin/bash、sh和.。这些方法在Linux和Windows(通过GitBash)环境下均适用。示例脚本展示了参数传递和处理,以及如何检查参数个数和使用特殊变量。文章还提到了通过添加脚本路径到$PATH环境变量来直接调用脚本。
摘要由CSDN通过智能技术生成

      有时会在一个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 1
fi

echo "执行文件名: $0"
echo "param1: $1"; echo "param2: $2"; echo "param3: $3"

parameters=$*

# 特殊字符用来处理参数
# $#: 传递到脚本的参数个数
echo "参数个数为: $#"
# $*: 以一个单字符串显示所有向脚本传递的参数
echo "传递的参数作为一个字符串显示: $*"
# $@: 与$*相同,但是使用时加引号,并在引号中返回每个参数
echo "传递的参数作为字符串显示: $@"

for i in "$*"; do # 循环一次
    echo "loop"; echo $i
done

echo ""
for i in "$@"; do # 循环三次
    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上的执行结果如下:

      在windows上执行结果如下:

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

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

  • 2
    点赞
  • 35
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值