5

I am executing a .sh script today. It is executed with prefix "./.sh,I am a bit confuse because it is also executed without ./.but why this is required to use ./

Could you please explain me that why ./ is used to run .sh scripts?

7
  • Because the current directory is not the first search location in the $PATH.
    – dobey
    May 20, 2014 at 13:44
  • 4
  • 7
    There is nothing off-topic about this question. If one wants to close just because it says "Unix", one needs to understand there is nothing so-unixy about this question. The question as-is is completely applicable for Ubuntu as well. Newcomers don't know a lot of distinction between Unix, Linux and other derivatives and they use the words inter-changeably. If one is concerned with the word "Unix" in title, edit it out!
    – Aditya
    May 20, 2014 at 14:08
  • The comment from @fedorqui points to an exact duplicate of this question... is it possible to mark duplicates across SE sites?
    – Rmano
    May 20, 2014 at 14:24
  • 3
    There does not appear to be anything off topic about this question but it may be a duplicate one candidate from this site is: Why do I need to type ./ before executing a program in the current directory? May 20, 2014 at 15:10

2 Answers 2

8

The ./ is needed to tell bash interpreter where the script is located. There is a fixed set of directories that bash interpreter will check to run a command.

If your script is not in one of these directories than it will not find you script unless you specify the path. The ./ is telling the bash interpreter that the script is in the current directory.

You could also run the script from any other directory by using the full path.

e.g. ./script.sh from within /path/to is the same as running /path/to/script.sh from anywhere if the script is located in /path/to.

You can run echo $PATH to get a list of all the directories the bash interpreter will check. If you move you script or place a symbolic link in one the directories you will be able to execute it just using the file name script.

2
  • 1
    ...right, and normally the current directory is not (and should not ) be in the $PATH, to avoid common mistakes (like shadowing system commands). So you have to explicitly ask for it.
    – Rmano
    May 20, 2014 at 14:21
  • Why is not ok to just run example.sh directly in a current dir, when it is ok to do somedir/example.sh in the current dir without the ./ first? I.e. without ./somedir/example.sh...
    – JohnyTex
    Nov 4, 2022 at 9:15
0

Using "./", means that you ask your file to be runned. But, your file has to be executable, else it will not work.

If your file is not executable, you will have to prefix your command with the program intended to run it. For your sh script, it will probably be : "/bin/sh myscript.sh" .

Not the answer you're looking for? Browse other questions tagged .