本文介绍了当使用source(相同的shell)或bash(子shell)调用脚本时,如何从脚本中读取当前文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个艰苦的尝试,因为我已经研究了几个小时并且找不到有效的解决方案,因此我结合了一些发现的解决方案,结果如下:

This is a hard one, as I have researched for a few hours and could not find a solution that works, so I combined a few of solutions that I found and this is the results:

"$( cd "$( dirname "${BASH_SOURCE[0]}" )" && dirname -- "$(readlink -f -- "$0")" )"

如果有人有一个简单的人,请分享,否则,请尽情享受!

If anyone has a simpler one, please share otherwise, enjoy!

推荐答案

我认为没有bash的解决方案在任何情况下都适用(例如,通过链接获取文件时),但是这种方法可能大部分时间都在工作:

I don't think that there is a solution for bash which works in every circumstance (for instance when sourcing a file via a link), but this approach might work most of the time:

$ {BASH_SOURCE [0]} 包含脚本的名称,其中包括PATH组件(以调用方式).如果是通过 $ PATH 搜索调用的,则它包含相应的PATH.因此, dirname"$ {BASH_SOURCE [0]}" 将是脚本所在的目录(相对路径或绝对路径).因此, readlink -f-$(dirname"$ {BASH_SOURCE [0]}'')将输出该目录的绝对路径.因此,将 other_script 定位在同一目录中将是:

${BASH_SOURCE[0]} contains the name of the script including PATH component, in the way it is invoked. If it was invoked via a $PATH search, it contains that respective PATH. Hence, dirname "${BASH_SOURCE[0]}" would be the directory, where the script is located (either as relative or absolute path). Consequently, readlink -f -- $(dirname "${BASH_SOURCE[0]}") would output the absolute path to this directory. Hence to locate other_script in the same directory would be:

source "$(readlink -f -- $(dirname "${BASH_SOURCE[0]}"))/other_script" # bash

您还标记了 zsh 的问题.在Zsh中,事情要简单一些.您可以在 $ 0 中找到脚本(加上目录部分).因此,目录的绝对路径将返回 $ 0:A ,为您提供

You tagged your question also for zsh. In Zsh, things are a bit simpler. You find your script (plus directory part) in $0. The absolute path of the directory is hence returned $0:A, giving you

source $0:A/other_script # zsh

当然,如果您仅需要此信息来采购其他脚本,则不需要获取 other_script 绝对路径.相对路径也可以.

Of course, if you need this information only for sourcing the other script, you don't need to get the absolute path to other_script. The relative path would do as well.

这篇关于当使用source(相同的shell)或bash(子shell)调用脚本时,如何从脚本中读取当前文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 16:02