在与当前脚本相同的目录中运行脚本 [英] Run a script in the same directory as the current script
问题描述
我在同一文件夹中有两个Bash脚本(由下载整个存储库的用户保存在某个位置):
I have two Bash scripts in the same folder (saved somewhere by the user who downloads the entire repository):
-
script.sh
由用户运行 -
helper.sh
是必需的,并由script.sh
运行
script.sh
is run by the userhelper.sh
is required and run byscript.sh
这两个脚本应该在同一目录中.我需要第一个脚本来调用第二个脚本,但是有两个问题:
The two scripts should be in the same directory. I need the first script to call the second one, but there are two problems:
- 知道当前工作目录对我毫无用处,因为我不知道用户如何执行第一个脚本(可能是
/usr/bin/script.sh
,./script.sh
,也可能是../Downloads/repo/scr/script.sh
) - 在调用
helper.sh
之前,脚本script.sh
将更改为其他目录.
- Knowing the current working directory is useless to me, because I don't know how the user is executing the first script (could be with
/usr/bin/script.sh
, with./script.sh
, or it could be with../Downloads/repo/scr/script.sh
) - The script
script.sh
will be changing to a different directory before callinghelper.sh
.
我绝对可以通过将当前目录存储在变量中来一起破解Bash,但这似乎是不必要的代码复杂,因为我认为这是一个非常常见和简单的任务.
I can definitely hack together Bash that does this by storing the current directory in a variable, but that code seems needlessly complicated for what I imagine is a very common and simple task.
是否存在从script.sh
内部可靠地 调用helper.sh
的标准方法?可以在任何Bash支持的操作系统中使用吗?
Is there a standard way to reliably call helper.sh
from within script.sh
? And will work in any Bash-supported operating system?
推荐答案
Since $0
holds the full path of the script that is running, you can use dirname
against it to get the path of the script:
#!/bin/bash
script_name=$0
script_full_path=$(dirname "$0")
echo "script_name: $script_name"
echo "full path: $script_full_path"
因此,例如,如果将其存储在/tmp/a.sh
中,则会看到类似以下的输出:
so if you for example store it in /tmp/a.sh
then you will see an output like:
$ /tmp/a.sh
script_name: /tmp/a.sh
full path: /tmp
如此
- 知道当前工作目录对我毫无用处,因为我不知道用户如何执行第一个脚本(可能与
/usr/bin/script.sh
(与./script.sh
一起使用),也可能与../Downloads/repo/scr/script.sh
)
- Knowing the current working directory is useless to me, because I don't know how the user is executing the first script (could be with
/usr/bin/script.sh
, with./script.sh
, or it could be with../Downloads/repo/scr/script.sh
)
使用dirname "$0"
将使您可以跟踪原始路径.
Using dirname "$0"
will allow you to keep track of the original path.
- 在调用
helper.sh
之前,脚本script.sh
将更改为其他目录.
- The script
script.sh
will be changing to a different directory before callinghelper.sh
.
同样,由于在$0
中具有路径,因此可以cd
返回到该路径.
Again, since you have the path in $0
you can cd
back to it.
这篇关于在与当前脚本相同的目录中运行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!