简体   繁体   中英

Change working directory to current script's directory

I have a top level bash script, say ScriptA, and a couple of other bash scripts in a sub directory, DY which is at the same level as Script A. Let's say the other bash scripts in DY are ScriptB and ScriptC. ScriptA will source both ScriptB and ScriptC at some point, and I want all the scripts to run in their respective directories. Here's an example:

ScriptA:

#!/bin/bash
touch script_a_1.txt
source DY/ScriptB.sh
touch script_a_2.txt
source DY/ScriptC.sh

ScriptB:

#!/bin/bash
touch script_b_file.txt

ScriptC:

#!/bin/bash
touch script_c_file.txt

So script_a_1.txt and script_a_2.txt should be in the directory ScriptA is in, and script_b_file.txt and script_c_file.txt should be in sub directory DY.

I have tried placing

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

at the top of ScriptB and ScriptC and in ScriptA when it comes back from ScriptB, but when returning to ScriptA, the working directory is still in DY instead of wherever ScriptA is in.

Any ideas on how to accomplish this?

EDIT

Bonus if the solution can also handle the case when running the script in a subprocess, ie ScriptA:

#!/bin/bash
touch script_a_1.txt
source DY/ScriptB.sh
touch script_a_2.txt
DY/./ScriptC.sh

*Also fixed the initial ScriptA example not sourcing ScriptC

Push the directory of ScriptB.sh onto the directory stack, then run the script, and pop when you're done.

pushd DY
source ./ScriptB.sh
popd

Nice and clean.

Also works for subprocesses:

pushd DY
./ScriptC.sh
popd

Well you could do something like this, kinda of dirty but a start point:

In script B & C just put:

cd subdirectory && touch ./your_file_name.log && cd ..

Anyway I'll be checking a better way to do it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM