在与当前脚本相同的目录中运行脚本 [英] Run a script in the same directory as the current script

查看:144
本文介绍了在与当前脚本相同的目录中运行脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在同一文件夹中有两个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 user
  • helper.sh is required and run by script.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:

  1. 知道当前工作目录对我毫无用处,因为我不知道用户如何执行第一个脚本(可能是/usr/bin/script.sh./script.sh,也可能是../Downloads/repo/scr/script.sh)
  2. 在调用helper.sh之前,脚本script.sh将更改为其他目录.
  1. 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)
  2. The script script.sh will be changing to a different directory before calling helper.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?

推荐答案

由于$0拥有正在运行的脚本的完整路径,因此可以使用

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

如此

  1. 知道当前工作目录对我毫无用处,因为我不知道用户如何执行第一个脚本(可能与 /usr/bin/script.sh(与./script.sh一起使用),也可能与 ../Downloads/repo/scr/script.sh)
  1. 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.

  1. 在调用helper.sh之前,脚本script.sh将更改为其他目录.
  1. The script script.sh will be changing to a different directory before calling helper.sh.

同样,由于在$0中具有路径,因此可以cd返回到该路径.

Again, since you have the path in $0 you can cd back to it.

这篇关于在与当前脚本相同的目录中运行脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆