如何获得在zsh中执行脚本的父文件夹? [英] How to get parent folder of executing script in zsh?

查看:346
本文介绍了如何获得在zsh中执行脚本的父文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在bash中我得到这个行执行脚本的父文件夹名称

In bash i get the executing script's parent folder name by this line

SCRIPT_PARENT=`readlink -f ${BASH_SOURCE%/*}/..`

有没有办法在这两个中的zsh和bash工作的方式zsh来实​​现这一目标?

Is there any way to achieve this in zsh in a way that works both in zsh and bash?

假设我有一个文件 /部分/文件夹/ rootfolder /子/脚本与内容:

Assume i have got a file /some/folder/rootfolder/subfolder/script with the contents:

echo `magic-i-am-looking-for`

我希望它这样的行为:

I want it to behave this way:

$ cd /some/other/folder
$ . /some/folder/rootfolder/subfolder/script
/some/folder/rootfolder
$ . ../../folder/rootfolder/subfolder/script
/some/folder/rootfolder
$ cd /some/folder/rootfolder
$ . subfolder/script
/some/folder/rootfolder
$ cd subfolder
$ . script
/some/folder/rootfolder

这应该在bash和zsh的工作。我的第一个实现了该行为,但由于 $ BASH_SOURCE 不是zsh的工作。

This should work in bash and zsh. My first implements this behavior, but does due to $BASH_SOURCE not work in zsh.

所以基本上它的:

有没有办法模仿 $ BASH_SOURCE 在zsh中,也适用在bash?

Is there a way to emulate $BASH_SOURCE in zsh, that also works in bash?

推荐答案

我现在意识到, $ 1,0 在zsh的行为像 $ BASH_SOURCE 在bash。因此,使用 $ BASH_SOURCE 可用,回落至 $ 1,0 解决我的问题时:

I now realized that $0 in zsh behaves like $BASH_SOURCE in bash. So using $BASH_SOURCE when available and falling back to $0 solves my problem:

${BASH_SOURCE:-$0}

有一个小的zsh边缘的情况下离开,从 $ PATH采购时这样的:

There is a little zsh edge case left, when sourcing from $PATH like:

zsh> cat ../script
echo \$0: $0
echo \$BASH_SOURCE: $BASH_SOURCE
echo '${BASH_SOURCE:-$0}:' ${BASH_SOURCE:-$0}
zsh> . script
$0: script
$BASH_SOURCE:
${BASH_SOURCE:-$0}: script
bash> . script
$0: bash
$BASH_SOURCE: /home/me/script
${BASH_SOURCE:-$0}: /home/me/script

我可以做一个哪个脚本但不会与其他情况下发挥不错

I could do a which script but this would not play nice with other cases

这篇关于如何获得在zsh中执行脚本的父文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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