Ubuntu – Running scripts from another directory

command linescripts

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

Best Answer

You can call your script using only the whole path, without the dot .:

/path/to/script

sudo also works fine:

sudo /path/to/script

Will they usually find all the stuff they need to run properly?

Do you mean like, "will my script find the files which are in the same folder?" That depends of your code. For example, if you have the script /tmp/test.sh:

#!/bin/bash
ls

If you invoke it from your home folder, it will run ls in your home:

test@ubuntu:~:/tmp/test.sh
Desktop     Dropbox         Imagens  NetBeansProjects     Público     
Documentos  Modelos    R          Vídeos

In this situation, dirname is your ally:

#!/bin/bash
current=$(dirname $0)
ls $current

Running it from your home folder, it gives:

test@ubuntu:~:/tmp/test.sh
acroread_1000_1000     hiRF7yLSOD              pulse-2L9K88eMlGn7   
unity_support_test.0    clementine-art-jt5332.jpg

which is the content of my /tmp/ folder.

Related Question