What is the difference between source, sh, bash, ./ in linux

In Linux, source, sh, bash, ./ can all execute shell script files, so what is the difference between them?

-----------

1、source

source a.sh

Read and execute a.sh in the current shell , and a.sh does not need " execute permission "

The source command can be abbreviated as "."

. a.sh

Note: there are spaces in between.

 

2、sh/bash

sh a.sh
bash a.sh

Both open a subshell to read and execute a.sh, and a.sh does not need " execute permission "

Usually setting variables in scripts running in the subshell will not affect the parent shell.

 

3、./

./a.sh 
#bash 
: ./a.sh : insufficient permissions
 chmod + x a.sh ./a.sh

Open a subshell to read and execute a.sh, but a.sh needs to have " execute permission "

Execute permission can be added with chmod +x

 

4、fork、source、exec

  • When using the fork mode to run the script, it is to let the shell (parent process) generate a child process to execute the script. When the child process ends, it will return to the parent process, but the environment of the parent process will not change due to the change of the child process. .
  • When using the source mode to run the script, it is to let the script execute in the current process, instead of generating a child process to execute. Since all execution results are completed in the current process, if the environment of the script changes, of course, the environment of the current process will also be changed.
  • When using the exec mode to run the script, it is the same as the source, which also allows the script to be executed in the current process, but the rest of the original code in the process will be terminated. Likewise, the environment within the process changes as the script changes.

Usually if we execute it, it defaults to fork.

In order to practice, we can first create two sh files, the following code is from the netizens of ChinaUnix :

1.sh

copy code
#!/bin/bash
A=B
echo "PID for 1.sh before exec/source/fork:$$"
export A
echo "1.sh: \$A is $A"
case $1 in
    exec)
        echo "using exec..."
        exec ./2.sh ;;
    source)
        echo "using source..."
        . ./2.sh ;;
    *)
        echo "using fork by default..."
        ./2.sh ;;
esac
echo "PID for 1.sh after exec/source/fork:$$"
echo "1.sh: \$A is $A"
copy code

2.sh

#!/bin/bash
echo "PID for 2.sh: $$"
echo "2.sh get \$A=$A from 1.sh"
A=C
export A
echo "2.sh: \$A is $A"

 

Run it yourself and watch the results :)

chmod +x 1.sh
chmod +x 2.sh
./1.sh fork
./1.sh source
./1.sh exec

Reprinted from: https://www.cnblogs.com/pcat/p/5467188.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326016109&siteId=291194637