2

Say I have a somecommands.sh and I use chmod 777 to make it executable. Why I have to type ./scommand.sh instead of typing just somecommand.sh to run it from its own directory?

Does this make any sense? If it's able to omit, what should I do?

Thanks

AGamePlayer
  • 7,605

2 Answers2

4

You have to likely do that, because your current path (pwd) is not in your search path for executable files.

Type this in your console:

echo $PATH | tr ':' '\n'

Every folder that is printed, is in the search path for executable files (in that order).

Now, if you want to run a file from a different directory, you have to supply the full (relative or absolute) path.

./script.sh

means the current directory (./, relative to where you are) and the the filename (script.sh). You can equally well use the full path (starting from the root folder /) to your file (for instance /home/guo/script.sh, if hat's your username, and when your file is in your home directory).

As a tip, if you regularly use that file, I suggest making a local /bin directory (~/bin, as inside your home directory) and then put export PATH="$HOME/bin:$PATH" into your .bashrc, for instance. And then put your scripts into that directory.

Another thing: I suggest not using 777 as permissions to run it. Instead I suggest 755, so only you have permission to overwrite the file. If you want to make a file executable just use chmod +x script.sh, it'll usually do what you want.

In a similar fashion as I've described above, it is possible to add the "current" directory, to path: export PATH=".:$PATH", but this is not advisable. I strongly advise, using a private directory (~/bin) for those use cases.

polemon
  • 11,431
2

In order to run any executable in Linux, you need to mention its full path (in case it is not stored in the $PATH variable).

In Linux, . stands for the directory that you are currently in and / is the path separator. So, with ./somecommands.sh, you tell the shell that, please run the executable somecommands.sh which is present in current directory.