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 ?
-
Related: What is the difference between running “bash script.sh” and “./script.sh”?steeldriver– steeldriver2017-05-10 12:47:38 +00:00Commented May 10, 2017 at 12:47
-
Also: What is the function of bash shebang? and Does the shebang determine the shell which runs the script?ilkkachu– ilkkachu2017-05-10 13:50:05 +00:00Commented May 10, 2017 at 13:50
1 Answer
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).