Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

shell

unix

Sometimes i see that few scripts are executed through "sh" command and sometimes through "./" command.I am not able to understand the exact difference between them.Please help me out .

like image 407
Shashank Vivek Avatar asked Feb 28 '14 05:02

Shashank Vivek


People also ask

What is difference between sh and sh?

sh file executes a shell-script file in a new shell process. . file executes a shell-script file in the current shell process. ./file will execute the file in the current directory.

What does sh do in Unix?

sh is a command language interpreter that executes commands read from a command line string, the standard input, or a specified file. The Bourne shell was developed in 1977 by Stephen Bourne at AT&T's Bell Labs in 1977. It was the default shell of Unix Version 7.

Where is sh used?

sh file is nothing but the shell script to install given application or to perform other tasks under Linux and UNIX like operating systems.


1 Answers

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

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

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


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

#!/bin/sh  TEST=present 

and you execute it with sh test.sh, you'd launch a new sh (or rather bash, most likely, as one is softlinked to the other in modern systems), then define a new variable inside it, then exit. A subsequent echo $TEST prints an empty line - the variable is not set in the outer shell.

If you launch it using . test.sh, you'd execute the script using the current shell. The result of echo $TEST would print present.

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

like image 143
Amadan Avatar answered Sep 19 '22 21:09

Amadan