bash 从一个目录执行bash脚本到另一个目录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20406079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 08:53:52  来源:igfitidea点击:

Execute bash script from one into another directory?

linuxbash

提问by vir2al

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.

我有 3 个目录:/A/B/C 和 C 目录中的 1 个 bash 脚本。如何将这个 bash 脚本从 A 执行到 C 目录中。

回答by Louis

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

我从您的评论中了解到,您希望脚本在A/B/C执行时将其当前工作目录置于其中。好的,所以你进入目录A:

cd A

and then execute script.shfrom there:

然后script.sh从那里执行:

(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.

这样做是启动一个子shell,您首先在其中切换到您希望脚本在其中执行的目录,然后执行该脚本。将其作为子shell 可防止它弄乱交互式会话的当前目录。

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.

如果它是一个长时间运行的脚本,您想保留在后台,您也可以&像任何其他命令一样在末尾添加。

回答by keyser

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

转到 A,然后通过提供它的路径来运行您的脚本:

cd /A
bash B/C/somescript.sh

You could also add Cto your PATHvariable, making it runnable from anywhere

您还可以添加C到您的PATH变量,使其可从任何地方运行

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

(即somescript.sh,没有路径)

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 thisthread. There are many more suggestions there.

或者干脆dirname。取自这个线程。还有更多的建议。

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

让您的脚本在其中执行的简单方法C是简单地位于该文件夹中。

回答by mikebabcock

Assuming /A/B/C/script.shis the script, if you're in /A, then you'd type ./B/C/script.shor bash B/C/script.shor 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 PATHvariable.

假设/A/B/C/script.sh是脚本,如果您在 中/A,那么您可以输入./B/C/script.shbash B/C/script.sh或完整路径,/A/B/C/script.sh。如果您的意思是希望该脚本始终有效,那么您需要将其添加到PATH变量中。

回答by bischoje

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 "##代码##")"

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

听起来这正是您要找的!