Difference between "./" and "sh" on UNIX

Sometimes I see that several scripts are executed using the "sh" command, and sometimes with "./". I can not understand the exact difference between the two. Please help me.

+7
unix shell
source share
2 answers

sh file executes a shell script file in a new shell process.

. file . file executes the shell script file in the current shell process.

./file will execute the file in the current directory. The file can be a binary executable file or it can start with the hashbang line (the first line of the file in the form #!.... , for example #!/usr/bin/ruby in the file means that the script should be executed as a Ruby file). An executable file flag must be set for the file.


For example, if you have a test.sh script:

 #!/bin/sh TEST=present 

and you run it with sh test.sh , you run a new sh (or rather bash , most likely, since it will be bound to another on modern systems), and then define a new variable in it, then exit. The next echo $TEST prints an empty string - the variable is not set in the outer shell.

If you run it with . test.sh . test.sh , you must execute the script using the current shell. The result of echo $TEST will print present .

If you run it with ./test.sh , the first line #!/bin/sh is detected, then it will be exactly as if you wrote /bin/sh ./test.sh , which in this case reduces to the first scenario. But if the hashbang line was, for example, #!/usr/bin/perl -w , the file would be executed using /usr/bin/perl -w ./test.sh .

+14
source share

In simple words, sh file1 , the sh / executable file command is executed with file 1 as a parameter. In this case, file1 does not require the right to run, since the sh executable reads and intercepts the commands in the file.

./file1 nothing but launching / executing the executable file1, therefore it requires executable privileges. In this case, it runs on the shell mentioned in shebang #!/bin/sh , if it is not mentioned then in the current shell.

Hoping the above statements are not chaos :)

+7
source share

All Articles