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

扫描二维码关注公众号,回复: 15542222 查看本文章
#!/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

猜你喜欢

转载自blog.csdn.net/shouhu010/article/details/131411708