Shell Script—脚本之间的相互调用

本文主要介绍在shell中,如何实现脚本之间的相互调用;

1.脚本函数调用

可以在一个脚本中定义一个或多个函数,然后可以从同一脚本中的其他函数或命令中调用它们。您还可以在不同的脚本中定义和调用函数。

示例

main.sh

#!/bin/bash

source ./t1.sh  #加载t1.sh
func_t1   #执行函数

t1.sh

#!/bin/bash

#定义函数
function func_t1 {
  echo "This is function t1 in script t1.sh."
}

执行sh main.sh输出结果为

This is function t1 in script t1.sh.

2.传递参数

可以使用参数将数据从一个脚本传递到另一个脚本。使用 $1$2,… $n 表示第一个、第二个、…第n个参数。

main.sh

#!/bin/bash

sh t2.sh  #执行脚本t2.sh,可以直接执行

t1.sh

#!/bin/bash

#定义函数
function func_t1 {
  echo "This is function t1 in script t1.sh."
}

t2.sh

#!/bin/bash

source ./t1.sh #加载脚本 t1.sh
func_t1 #调用脚本 t1.sh 中的函数

source ./t3.sh #加载脚本 t3.sh
func_t3 "apple" "orange" "banana" #调用脚本 t3.sh 中的函数

t3.sh

#!/bin/bash

function func_t3 {
  echo "This is function t3 in script t3.sh."
  
  echo "The first argument from t2.sh is: $1"
  echo "The second argument from t2.sh is: $2"
  echo "The third argument from t2.sh is: $3"
}

执行sh main.sh输出结果为

This is function t1 in script t1.sh.
This is function t3 in script t3.sh.
The first argument from t2.sh is: apple
The second argument from t2.sh is: orange
The third argument from t2.sh is: banana

3.使用 source 命令调用脚本

使用 source 命令加载一个脚本,使得可以在当前脚本中使用所加载脚本中的变量和函数。

例如,可以在脚本t1.sh中定义一些变量和函数,然后在脚本main.sh中使用source命令来加载脚本t1.sh并使用这些变量和函数;

示例
main.sh

#!/bin/bash

source ./t1.sh

func_t1

echo ${NUM}

echo ${str_path}

echo ${array[@]}

t1.sh

#!/bin/bash

NUM=12

str_path="/home/etc/"

array=("student","class","source")

function func_t1 {
  echo "This is function t1 in script t1.sh."
}

执行sh main.sh输出结果为

This is function t1 in script t1.sh.
12
/home/etc/
student,class,source
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值