Difference between ./executable and . executable

試著忘記壹切 提交于 2019-12-07 12:43:35

问题


In a shell, what is the difference between?

. executable

and

./executable

In the first one, the dot a shortcut for source right? So is there a difference between ./executable and source executable?


回答1:


is there a difference between ./executable and source executable?

basic difference is,

./foo.sh      - foo.sh will be executed in a sub-shell
source foo.sh - foo.sh will be executed in current shell

some example could help to explain the difference:

let's say we have foo.sh:

#!/bin/bash
VAR=100

source it:

$ source foo.sh 
$ echo $VAR
100

if you :

./foo.sh
$ echo $VAR
[empty]

another example, bar.sh

#!/bin/bash
echo "hello!"
exit 0

if you execute it like:

$ ./bar.sh
hello
$

but if you source it:

$ source bar.sh
<your terminal exits, because it was executed with current shell>



回答2:


./executable runs an executable which is in the current working directory. (executable is not enough for that if there is no . in your $PATH, and usually there isn't). In this case, executable can be an elf binary, or a script starting with #!/some/interpreter, or anything you can exec (on Linux it's potentially everything, thanks to binfmt module).

. executable sources a shell script into your current shell, whether it has execute permissions or not. No new process is created. In bash, script is searched according to the $PATH variable. Script may set environment variables which will remain set in your shell, define functions and aliases and so on.




回答3:


In the second one you give the path: ./ is the current working directory so it doesn't search in PATH for the executable but in the current directory.

source takes the executable as a parameter and executes it in the current process.



来源:https://stackoverflow.com/questions/14625580/difference-between-executable-and-executable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!