How to run a .sh-script from any path in a terminal?

You have to copy or link the script into a directory that is on the $PATH. Usually /usr/bin and /usr/local/bin/ are on the path so these are good locations to link or copy the script to.

ln -s /path/to/your/script /usr/local/bin

If you are not root you will either need to sudo that command or run it as the root user.


One option is simply to type the path to the script:

~/Desktop/script

This works fine, but gets a bit unwieldy.

This is what the PATH environment variable is for. And it is what $HOME/bin is for.

  1. Create yourself a directory $HOME/bin. Put all your executable scripts in it (make them executable with chmod +x script if need be††). This way, there's one place to look for the scripts you want to run.
  2. Add $HOME/bin to your PATH. I put mine at the front: PATH="$HOME/bin:$PATH, but you could put it at the back if you prefer.
  3. Update your .profile or .bash_profile (or possibly .bashrc) file to set PATH. Beware of a continually growing PATH, though.

As tripleee noted, once the command is installed in a directory on PATH, you no longer type ./script, but just script. This is exactly like you type ls and not /bin/ls, etc. Once the program is installed in a directory on your PATH, it is (for many purposes) indistinguishable from a system-provided command.

I have about 500 scripts and programs in my $HOME/bin directory.

Note that this doesn't require any special privileges. If you have administrator access to your machine and you think other users might find your commands useful, then you could install the scripts/programs in one of the system-provided directories on your PATH. However, it is usually best not to add programs to any of:

  • /bin
  • /usr/bin
  • /sbin
  • /usr/sbin

There is often/usually /usr/local/bin which is a suitable place for widely used commands not provided by the system.


†† It would be better to use chmod a+x,go-w script; your scripts should not be writable by other people. You could even simply use chmod 555 script or chmod 755 script. I tend to keep my scripts non-writable. That way, I have to go through a formal change process with the version control system. It means there's less danger of uncontrolled changes.