vir2al
vir2al

Reputation: 837

Execute bash script from one into another directory?

I have 3 directories: /A/B/C and 1 bash script in C directory. How can I execute this bash script from A into in C directory.

Upvotes: 3

Views: 11742

Answers (4)

bischoje
bischoje

Reputation: 197

Whenever I want to make sure that a script can access files in its local folder, I throw this in near the top of the script:

# Ensure working directory is local to this script
cd "$(dirname "$0")"

It sounds like this is exactly what you're looking for!

Upvotes: 4

Louis
Louis

Reputation: 151380

I understand from your comments that you want your script to have its current working directory to be in A/B/C when it executes. Ok, so you go into directory A:

cd A

and then execute script.sh from there:

(cd B/C; ./script.sh)

What this does is start a subshell in which you first change to the directory you want your script to execute in and then executes the script. Putting it as a subshell prevents it from messing up the current directory of your interactive session.

If it is a long running script that you want to keep in the background you can also just add & at the end like any other command.

Upvotes: 4

keyser
keyser

Reputation: 19189

Go to A, then run your script by providing the path to it:

cd /A
bash B/C/somescript.sh

You could also add C to your PATH variable, making it runnable from anywhere

(i.e. somescript.sh, without the path)

If you want to access the directory the script is stored in, within the script, you can use this one-liner:

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

or simply dirname. Taken from this thread. There are many more suggestions there.

The easy way to make your script execute within C is to simply be in that folder.

Upvotes: 0

mikebabcock
mikebabcock

Reputation: 791

Assuming /A/B/C/script.sh is the script, if you're in /A, then you'd type ./B/C/script.sh or bash B/C/script.sh or a full path, /A/B/C/script.sh. If what you mean is that you want that script always to work, then you'll want to add it to your PATH variable.

Upvotes: 0

Related Questions