2 ways to reference and call another script file in Shell script

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

 

copy code code show as below:

>>> import math  
>>> math.sqrt(4)  
2.0  


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

 

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

Notice:

1. There is a space between the two dots. Be careful.
2. The two scripts are not in the same directory, so use an absolute path
. 3. For simplicity, the first method is usually used.

E.g:

copy code code show as below:

main.sh #Main script
subscripts.sh #Subscript, or called script 
[code]
[code]
###subscripts.sh The script content is as follows: ###  
  
#!/bin/bash  
string="Hello, World! \n"  

 

 

copy code code show as below:

###main.sh The script content is as follows ###  
  
#!/bin/bash  
. ./subscripts.sh  
echo -e ${string}  
exit 0  


Output result:

copy code code show as below:

# chmod +x ./main.sh  
# ./main.sh  
Hello,World!  
#  

 

注意:

1.被调脚本可以没有执行权限,调用脚本必须有可执行权限
2.chmod +x ./main.sh   #注意这里要有点,否则bash脚本可能找不到

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326676430&siteId=291194637