Question: Quite often, the script I want to execute is not located in my current working directory and I don't really want to leave it.

Is it a good practice to run scripts (BASH, Perl etc.) from another directory? Will they usually find all the stuff they need to run properly?

If so, what is the best way to run a "distant" script? Is it

```
. /path/to/script

```

or

```
sh /path/to/script

```

and how to use `sudo` in such cases? This, for example, doesn't work:

```
sudo . /path/to/script

```

Answer: 
If you have scripts lying around that you need to run often, and they depend on their location for finding resources you can easily do this by just combining commands in an alias like this.

```
alias run-script="cd /home/user/path/to/script/ && bash script.sh"

```

This way you don't have to alter anything else to make it work.
Ancient question, but a timeless one.

The solution I've consistently seen is to have a `$HOME/bin` directory and put it first in `$PATH` (via `~/.bashrc` if it isn't already there; on some systems `~/bin` is first in `$PATH` by default). Dropping scripts in there for execution or symlinks to scripts/executables elsewhere is the simple way to deal with path issues that shouldn't affect the system or other users.

If a script requires additional resources that can be found *relative to its own location* (not uncommon) then the envvar `$BASH_SOURCE` is used. `$BASH_SOURCE` always contains the absolute path to the currently running script itself, regardless the value of `$PWD`.

Consider the following:

```
ceverett@burrito:~$ echo $PATH
/home/ceverett/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

```

So we can see that `$HOME/bin` is first in `$PATH`, so whatever I put in `~/bin` will run. I have a demonstration script called `~/bin/findme`:

```
#!/bin/bash

echo "Running from $BASH_SOURCE"

```

This can be used to get the absolute path to the running script's location.

```
ceverett@burrito:~$ findme
Running from /home/ceverett/bin/findme
ceverett@burrito:~$ cd foo
ceverett@burrito:~/foo$ findme
Running from /home/ceverett/bin/findme
ceverett@burrito:~/foo$ cd /
ceverett@burrito:/$ findme
Running from /home/ceverett/bin/findme

```