Two methods of referencing and calling another script file in shell script

Time:2022-1-15

In Java and python, you can use import to call between scripts or modules, for example:

Copy codeThe code is as follows:
>>> import math 
>>> math.sqrt(4) 
2.0 

How to call other shell scripts, or variables and functions in other scripts in the shell?

Method 1:/ subscript. sh     
Method 2: source/ subscript. sh

be careful:

1. There is a space between two points. Please pay attention
2. If the two scripts are not in the same directory, use the absolute path
3. For simplicity, the first method is usually used

For example:

Copy codeThe code is as follows:
main. SH # main script
subscripts. SH # sub script, or called script
[code]
[code]
###subscripts. The SH script is as follows: ###
 
#!/bin/bash 
string=”Hello,World! \n” 

Copy codeThe code is as follows:
###main. The SH script is as follows ###
 
#!/bin/bash 
. ./subscripts.sh 
echo -e ${string} 
exit 0 

Output results:

Copy codeThe code is as follows:
# chmod +x ./main.sh 
# ./main.sh 
Hello,World! 

be careful:

1. The called script may not have execution permission, and the calling script must have executable permission
2.chmod +x ./ main. SH # pay attention to this, otherwise the bash script may not find it