How to reuse external shell scripts under Linux

Time:2021-9-17

In Linux development, shell scripts are often written to perform some tasks. Usually, a script only does one thing. With the increase of tasks, there will be more and more scripts and more reusable places. At this time, it is necessary to extract the common functions in the script and put them into a general script, which can be reused by other scripts
Linux命令
This article introduces how to execute external scripts in shell scripts, how to call functions in external scripts, and methods related to script reuse

How to execute external scripts

If there is in the current directorya.shScript, as follows

#!/bin/bashecho "a.sh..."

There are several ways to execute external scripts in a script

  • Source external script name

In the current directoryb.shScript, as follows:

#!/bin/bashsource a.shecho "b.sh..."

implement./b.sh, the results are as follows

[[email protected] ~]# ./b.sh a.sh...b.sh...

In scriptsource a.shThe command will execute the command in the current directory firsta.shScript, so the results will be output firsta.sh...Re outputb.shPrinting of the script itself

  • Dot external script name

holdb.shExecute in scripta.shThe statement of the script is modified toDot + space + a.sh, the modified script is as follows:

Note: point number anda.shBe sure to add a space between them, otherwise an error will occur during execution

#!/bin/bash. a.shecho "b.sh..."

implement./b.sh, the results are as follows

[[email protected] ~]# ./b.sh a.sh...b.sh...

In the above script,. a.shWill execute firsta.shScript, the results will be output firsta.sh...Re outputb.sh...

  • SH external script name

SH external script nameand. / external script nameThe two methods are the same. It’s OK to choose either method. The following is an example of the previous method

holdb.shIn scriptsource a.shModified intosh a.sh, the modified script is as follows:

#!/bin/bashsh a.shecho "b.sh..."

implement./b.shCommand, the result is as follows

[[email protected] ~]# ./b.sh a.sh...b.sh...

It can be seen that the result output is the same as the above two methods

What is the difference between the three methods

Calling an external script hasSource external scriptDot external scriptSH external scriptWhat is the difference between the three methods?

Among them,Source external scriptandDot external scriptThe two methods are the same. The current script inherits the global variables and functions of the external script, which is equivalent to importing the functions and global variables of the external script into the current script

modifya.shandb.shScript, as follows

a. SH script

#!/bin/bashVAR_A=10func_a(){  echo "a.sh...pid:$$,param:$1"}

b. SH script

#!/bin/bashsource a.sh func_a $1echo "vara:$VAR_A"echo "b.sh...pid:$$"

implement./b.sh 5Command, the result is as follows

[[email protected] ~]# ./b.sh 5a.sh...pid:21485,param:5vara:10b.sh...pid:21485

$$in the two scripts refers to the process ID of executing the script. As can be seen from the results,a.shandb.shAre executed in the same process, sob.shExecute in scriptsource a.shCommand, willa.shGlobal variables in scriptsVAR_ASum functionfunc_aImport tob.shin

stayb.shPrint variables inVAR_A, output values anda.shSame as in, callfunc_aFunction, the output also indicates that thea.shFunctions in

Source external scriptDot external scriptThe two ways are the same, so putb.shinsource a.shModified into. a.sh, execute./b.sh 5, the results are still the same

becauseSH external scriptThe method is that the current script and the external script are executed in two different processes, so the current script cannot directly use the functions and global variables in the external script

modifya.shandb.shScript, as follows

a. SH script

#!/bin/bashtest_a(){  echo "a.sh...test_a"}echo "a.sh...pid:$$"

b. SH script

#!/bin/bashsh a.shecho "b.sh...pid:$$"test_a

implement./b.shCommand, the result is as follows

[ [email protected] -Centos-7 ~]#. / b.sh a.sh... PID: 21818b. Sh... PID: 21817. / b.sh: Line 7: Test_ a: Command not found

As can be seen from the results, the implementationa.shandb.shThe process ID of is different,b.shScript process not foundtest_aFunction, so inb.shCall intest_aFunction will promptCommand not found

Calling a function in an external script

As mentioned in the previous sectionSH external scriptFunctions and global variables in external scripts cannot be used directly. The following methods are provided to solve this problem

  • Case branch selection

This method is similar to the switch case statement in the program code. Different branches are selected by switch to execute different logic. The case keyword is used in the shell script

a. SH script

#!/bin/bashVAR_A=10test_a(){   echo "test_a..pid:$$,p1:$1,p2:$2"}get_var(){  echo ${VAR_A}}case "$1" in    ta)      test_a $2 $3      ;;    var)      get_var      ;;   *)      echo "parameter err..."esac

b. SH script

#!/bin/bashecho "b.sh...pid:$$"sh a.sh ta 3 5ret=$(sh a.sh var)echo "ret:$ret"

implement./b.shCommand, the result is as follows

[[email protected] ~]# ./b.sh b.sh...pid:24813test_a..pid:24814,p1:3,p2:5ret:10

scriptb.shThe process ID of the calling itself is printed at the beginning

sh a.sh ta 3 5Statement is a calla.shScript, the three parameters passed in areta, 3, 5, executea.shThe first parameter passed in whentaAfter the case match, the call is made.test_aFunction and take the remaining two parameters3and5Pass in the function as an argument

ret=$(sh a.sh var)Called on statementa.shScript, passing in avarThe parameters are called after case matching.get_varFunction to output the global variables in the scriptVAR_AValue of, in statement$()The function of is to obtain()The return value of the command ina.shIn scriptget_varThe return value of the function is assigned toretVariable, so the value of the variable isa.shGlobal variables in scriptsVAR_AValue of

Note: if you want to get the return value of the function, you can use it in the functionechoPrint the corresponding output value, and then use$(function name parameter list)You can get the value printed in the function, as shown aboveb.shIn scriptret=$(sh a.sh var)Statement, variableretThe value of isa.shIn scriptget_varFunction output value 10

Note here that if there isechoDebug log, then the debug log will be returned together

  • Function call template

Using the case keyword to match and call different functions described above has a disadvantage. Each timea.shWhen a function is added to the script, the case needs to add a branch. Different functions are called in the branch. You also need to pay attention to whether the function has parameters passed in and whether the number of parameters is correct

We can solve the above problem by adding the following statement at the end of each script for external call. The specific statement is as follows

if [ $# -ge 1 ]; then   name="$1"   shift 1   $name "[email protected]"fi

The above statement first judges the number of parameters passed in when calling the script. It is valid only if the number of parameters is greater than or equal to 1. The first parameter passed in represents the function name. From the second parameter to the last parameter will be passed into the function as a parameter

thereshift 1Is to move the parameters of the incoming script to the left. For example, the parameters of the incoming script have$1 $2 $3Three parameters, after moving one position to the left,$2Move to$1The location of the,$3Move to$2The number of parameters has changed to 2

Reason: among the parameters passed into the script, the first parameter is the function name, and it is the function parameter from the second parameter. If you do not shift left, the first parameter function name will also be passed into the function as a parameter

Here is the complete script

a. SH script

#!/bin/bashVAR_A=10test_a(){   echo "test_a..pid:$$,p1:$1,p2:$2"}get_var(){  echo ${VAR_A}}if [ $# -ge 1 ]; then   name="$1"   shift 1   $name "[email protected]"fi

b. SH script

#!/bin/bashecho "b.sh...pid:$$"sh a.sh test_a 3 5ret=$(sh a.sh get_var)

implement./b.shCommand, the result is as follows

[[email protected] ~]# ./b.sh b.sh...pid:25086test_a..pid:25087,p1:3,p2:5ret:10

It can be seen that the result is the same as the case method above

Now you can use it in other scriptsSH a.sh function name parameter listCalled in this waya.shThe functions in the script are passed$(SH a.sh function name parameter list)Get bya.shReturn value of script function

  • Advantages and disadvantages of both

Compared with case branch selection, the advantage of function call template is that the caller only needs to care about the function name, function incoming parameters and function return value in the reused script

The disadvantage is that if multiple scripts call the function in the reuse script, when the function name in the reuse script changes, you need to modify all places that call it

The disadvantage of the function call template method is the case branch selection method. When selecting the case branch, different functions are called according to the incoming string parameters. The string parameters here are equivalent to the alias of the function. As long as this parameter remains unchanged, the function name in the script can be changed arbitrarily

The above comparison of advantages and disadvantages is only a relative comparison, which will not be obvious in practical application. In most cases, both methods can be used

Summary

In the process of writing shell scripts, we often encounter some inexplicable problems. Even if we scratch our scalp, we don’t know how to solve some problems. Script reuse can extract some public functions and form functional modules one by one, which not only helps to reduce the mistakes we make when writing scripts, but also is very helpful for later script maintenance

The above isLiangxu tutorial networkShare how to reuse external shell scripts under Linux.

This article is composed of blog one article multi posting platformOpenWriterelease!

Recommended Today

Supervisor

Supervisor [note] Supervisor – H view supervisor command help Supervisorctl – H view supervisorctl command help Supervisorctl help view the action command of supervisorctl Supervisorctl help any action to view the use of this action 1. Introduction Supervisor is a process control system. Generally speaking, it can monitor your process. If the process exits abnormally, […]