Understand the difference between source
and execute a script is important, otherwise you will be confused why something doesn’t run as you expect.
Source Script
The file may not necessary to be a executable (chmod -x
) but should be valid shell script. We usually use source
to load shell functions and export environment variables into current shell process.
For example, both syntax are good:
1 | source ./xx.env |
注意source
在当前上下文中执行脚本,不会生成新的进程!!执行完毕后回到当前进程。
Note that
.
is not an alias forsource
, but rather the other way around.source
is a bash extension, while.
works in any POSIX compatible shell.
You can also put the file path in $PATH
so that you don’t need to specify the path in command.
Execute Script
The file is executable (chmod +x
) and you are in right permission to run it. And you need to specify the path even in current directory, or put path in $PATH
:
1 | ./xx.sh |
The current shell spawns a new shell to run the script. The script is running in the new shell and all changes to the environment only in the new shell. After the script is done all changes to the environment in the new shell are destroyed.
Summary
Use execution method will run the script as another process, so variables and functions in child script will not be accessible in parent shell.
The source
method executes the child script in the parent script’s process, the parent process can access the variabels or functions in child script. If you are using exit
in script, it will exit the parent script as well. Which will not happen in execution method.
exec Command
exec
command, 这个命令在docker container的entry script中很常见:
- https://www.youtube.com/watch?v=nwm7rJG90i8
- https://askubuntu.com/questions/819910/what-are-possible-use-of-exec-command
此外还有su-exec
命令,但这个不是built-in的:
https://github.com/ncopa/su-exec