Software and Hardware Environment
- Ubuntu 18.04 64 – bit
- shell
Watch the video here
Here is the YouTube play link, need scientific Internet. If you like my videos, please remember to subscribe to my channel, turn on the little bell next to it, like it and share it, thanks for your support.
Introduction to the
In Linux, it is quite common for a shell script to call another shell script, and this article will share several ways to do so.
First prepare a script sub.sh to be called
#! /bin/bash echo "I am sub shell script."Copy the code
Methods a
Use the source command with the following code to call sub.sh in main.sh
#! /bin/bash echo "I am main shell script." source sub.shCopy the code
Run the main.sh command
bash main.sh
Copy the code
The result of execution is
(base) xugaoxiang@1070Ti:~/workshop/scripts$ bash main.sh
I am main shell script.
I am sub shell script.
Copy the code
Note that sh main.sh is not used above, because in Ubuntu 18.04 sh points to Dash
(base) xugaoxiang@1070Ti:~/workshop/scripts$ls -l /bin/sh LRWXRWXRWX 1 root root 4 March 24 15:21 /bin/sh -> dashCopy the code
If you want sh to point to bash, you can do so, using the following command
sudo dpkg-reconfigure dash
Copy the code
Then check again to see if the modification is successful
(base) xugaoxiang@1070Ti:~/workshop/scripts$ls -l /bin/sh LRWXRWXRWX 1 root root 4 8月 25 15:40 /bin/sh -> bashCopy the code
Method 2
Use the dot. Note that there is a space between the dot and the script being called
#! /bin/bash echo "I am main shell script." . sub.shCopy the code
The execution result is exactly the same as method 1
Methods three
Use the shell to display the call
Use bash sub.sh in main.sh
#! /bin/bash echo "I am main shell script." bash sub.shCopy the code
The result of execution is the same
note
Of the three methods mentioned above, method one and method two are essentially the same. Main. sh copies the contents of the sub.sh script and executes it by a shell process. To verify this, let’s simply modify sub.sh to go to Sleep 100
#! /bin/bash echo "I am sub shell script." sleep 100Copy the code
Use source or in main.sh. When invoked, main.sh is visible through the ps command, but there is no sub.sh process
Using the bash command to call the script sub.sh is fundamentally different from the first two methods. Using the bash command starts a new shell process to execute the script.