如何访问在 Bash 中采购的文件的基本文件名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1178751/
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-17 21:04:46  来源:igfitidea点击:

How can you access the base filename of a file you are sourcing in Bash?

linuxbashcommand-lineenvironment-variables

提问by hacintosh

I am sourcing a file in a bash terminal that needs to export some environment varibles.

我正在 bash 终端中获取一个文件,该文件需要导出一些环境变量。

Example:

例子:

source linux_x86.env

the env file looks kinda like this:

env 文件看起来有点像这样:

export ARCH=/home/user/project/linux_x86

I have a bunch of different architectures to compile for and I want be able to do something like this:

我有一堆不同的架构要编译,我希望能够做这样的事情:

export ARCH=/home/user/project/`basename 
bash linux_x86.env
linux_x86
.env`

where basename $0 .envwould give me the basename the env file

哪里basename $0 .env会给我 env 文件的基本名称

##代码##

The above will work is a bash script but doesn't seem to work when you source the file.

上面的内容是一个 bash 脚本,但在您获取文件时似乎不起作用。

Is there any way to get the same behavior from source?

有没有办法从源头获得相同的行为?

回答by Andrew Barnett

See Getting the source directory of a Bash script from within, particularly the comment regarding the BASH_SOURCE variable.

请参阅从内获取 Bash 脚本的源目录,特别是有关 BASH_SOURCE 变量的注释。

Summary: SCRIPT_NAME=$(basename ${BASH_SOURCE[0]})

概括: SCRIPT_NAME=$(basename ${BASH_SOURCE[0]})