简体   繁体   中英

What is the difference between “. file” and “./file” in Linux bash shell?

When 'file' is executable, what is the difference between

$ ./file

and

$ . file

in Linux bash shell?

. is alias for source : it will execute the file that is its argument in the current bash process, just as if you typed the file out in the command line directly.

./file is just giving a path to a file; in that case, the file is launched as a subprocess, according to the file's type, or its hashbang in case of a text file. If the first line of the file is #!/bin/bash , it will launch it as a new bash process.

./ here just says the file is in the current directory. Saying cd /bin ; ./ls cd /bin ; ./ls is no different than saying /bin/ls (except obviously for the fact that we change the current directory in one and not the other). The reason why we have to specify the current directory and can't simply give the file's name is that if there is no directory specified, bash only looks in PATH for programs to execute, and current directory is not normally in PATH in Unix-like systems. Since /bin is in PATH, a simple ls is (normally) equivalent to /bin/ls .

The difference is pretty stark if you want to define variables. Any environment variables only live for the current process and its subprocesses; so if you define an environment variable in a subprocess, the calling process will not have access to it.

For example, let's say you have a file called testvar.sh :

#!/bin/bash

what=world

If you do this, you will not have the variable set:

./testvar.sh ; echo Hello, $what
# => Hello, 

But if you do this, you will:

. testvar.sh ; echo Hello, $what
# => Hello, world

Another obvious difference is, since . executes bash commands, that it only works on files containing bash scripts. Thus, cd /bin ; ./ls cd /bin ; ./ls will execute the ls program; but cd /bin ; . ls cd /bin ; . ls cd /bin ; . ls will fail with an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM