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.
-
1Could you give an example of what you're asking? When you say "execute this bash script from A" do you mean you want to relocate the bash script to be under `A`? And then you want to run it on files in `C`? – lurker Dec 05 '13 at 17:02
-
mbratch, yes, I want to run it on files in C, but execute the script from A(the script is in C). When I'm in A I haven't the files(they are in C) with wich the cript works. (mv: cannot stat `*.cpp': No such file or directory .. i.e.) – vir2al Dec 05 '13 at 17:06
-
You have to give the relative path of the files, too. So something like `B/C/myscript.sh B/C/*.cpp`. But without an example of what you're trying to do, it's hard to tell. – lurker Dec 05 '13 at 17:11
4 Answers
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.

- 146,715
- 28
- 274
- 320
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!

- 197
- 1
- 8
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.
-
but the script needs some files, which are located in C and when I execute: B/C/somescript.sh from A directory it gives me an error: mv: cannot stat `*.cpp': No such file or directory .. i.e. beacause the script expects that I'm in C. – vir2al Dec 05 '13 at 17:09
-
@user1817479 Then you want your script to be aware of its own directory, or run it from C. – keyser Dec 05 '13 at 17:10
-
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.

- 791
- 1
- 7
- 20