3

I see people running shell scripts by typing ./scriptname. Now this seems to be the default way, since I have seen it so often, however occasionally, but not rare, I see them type sh scriptname. Is it just a matter of preference or is there a more significant difference between ./ and sh ?

sharkant
  • 3,710

1 Answers1

11

There are a few differences.

./scriptname

requires that the file called scriptname be executable, and it uses the shell specified as its first line (in the “shebang”, e.g. #!/bin/sh), if any.

sh scriptname

works as long as the file called scriptname is readable, and it uses sh (whatever that is) regardless of what the script’s shebang specifies. With some shells, if scriptname doesn’t exist in the current directory, the directories specified in PATH will be searched, and the first scriptname found there (if any) will be read and interpreted instead.

Put another way,

sh scriptname

will work without setup, but you might use the wrong shell, and you might run the wrong script.

./scriptname

will try to run the correct script using the right shell (or at least, the shell specified by the script’s author, if any), but it might need some setup first (chmod a+x scriptname).

Stephen Kitt
  • 434,908