简体   繁体   English

将工作目录更改为当前脚本的目录

[英]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. 我有一个顶级bash脚本,例如ScriptA,在子目录DY中有两个其他bash脚本,它们与脚本A处于同一级别。假设DY中的其他bash脚本是ScriptB和ScriptC。 ScriptA will source both ScriptB and ScriptC at some point, and I want all the scripts to run in their respective directories. ScriptA有时会同时提供ScriptB和ScriptC,我希望所有脚本都在各自的目录中运行。 Here's an example: 这是一个例子:

ScriptA: 脚本A:

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

ScriptB: 脚本B:

#!/bin/bash
touch script_b_file.txt

ScriptC: 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. 因此script_a_1.txt和script_a_2.txt应该在ScriptA所在的目录中,而script_b_file.txt和script_c_file.txt应该在子目录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. 从ScriptB返回时,位于ScriptB和ScriptC的顶部以及ScriptA中,但返回ScriptA时,工作目录仍位于DY中,而不是ScriptA所在的位置。

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: 如果解决方案还可以在子进程(例如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 *还修复了最初的ScriptA示例而不采购ScriptC

Push the directory of ScriptB.sh onto the directory stack, then run the script, and pop when you're done. ScriptB.sh的目录推到目录堆栈中,然后运行脚本,并在完成后弹出。

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: 在脚本B和C中,只需输入:

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

Anyway I'll be checking a better way to do it 无论如何,我会寻找一种更好的方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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