views:

139

answers:

2

Please tell me what is the difference in bash shell between launching a script with ./script.sh and . ./script.sh?

+4  A: 

The first requires the file to have the +x flag set. The second uses the . command aka "source", described here.

klausbyskov
Although that's true, the more important distinction is that "source" reads and executes the file in the current shell instance. Executing the script launches a new instance of the shell (as specified on the shebang line) in which the script is executed.
Dan Moulding
@Dan, yes that's right, and is also explained in the link i posted.
klausbyskov
That's the `-x` *permission* flag, not the bash -x *option* just to be clear.
Dennis Williamson
+11  A: 

As klausbyskov says, the first form requries that the file have its executable permission bit set.

But more importantly, the first form executes the script in a separate process (distinct from, independent of, and unable to make changes in the shell that launched it). The second form causes the initial shell to directly run the commands from the file (as if you had typed them into the shell, or as if they were included in the script that does the ‘sourcing’).

A script that contains FOO=bar; export FOO will have not create an exported FOO environment variable in the shell that runs the first variant, but it will create such a variable in a shell that runs the second variant.

The second form (‘sourcing’) is a bit like a #include in C.

Chris Johnsen