Shell Script—mutual calls between scripts

This article mainly introduces how to implement mutual calls between scripts in the shell;

1. Script function call

One or more functions can be defined in a script, which can then be called from other functions or commands in the same script. You can also define and call functions in different scripts.

example

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."
}

The execution sh main.shoutput is

This is function t1 in script t1.sh.

2. Pass parameters

Data can be passed from one script to another using parameters. Use $1, $2, ... $nto denote the first, second, ... nth argument.

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"
}

The execution sh main.shoutput is

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. Use the source command to call the script

Use sourcethe command to load a script so that the variables and functions in the loaded script can be used in the current script.

For example, you can t1.shdefine some variables and functions in the script, and then main.shuse sourcecommands in the script to load the script t1.shand use these variables and functions;

Example
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."
}

The execution sh main.shoutput is

This is function t1 in script t1.sh.
12
/home/etc/
student,class,source

Guess you like

Origin blog.csdn.net/shouhu010/article/details/131411708