看过用 .sh 文件设置环境变量和如何永久设置环境变量后,我仍然对如何从.sh
文件中正确设置永久环境变量感到困惑(我经常使用 linux,所以我肯定是一个新手)。
在我的具体情况下,我有一个setup-env.sh
:
# Copyright (c) 2015-2019 LunarG, Inc.
# source this file into an existing shell.
VULKAN_SDK="$(dirname "$(readlink -f "${BASH_SOURCE:-$_}" )" )/x86_64"
export VULKAN_SDK
PATH="$VULKAN_SDK/bin:$PATH"
export PATH
LD_LIBRARY_PATH="$VULKAN_SDK/lib:${LD_LIBRARY_PATH:-}"
export LD_LIBRARY_PATH
VK_LAYER_PATH="$VULKAN_SDK/etc/vulkan/explicit_layer.d"
export VK_LAYER_PATH
我可以编辑/home/jonathan/.bashrc
以包含:
export VK_LAYER_PATH="/home/jonathan/Vulkan/1.2.170.0/x86_64/etc/vulkan/explicit_layer.d"
export VULKAN_SDK="/home/jonathan/Vulkan/1.2.170.0/x86_64"
export LD_LIBRARY_PATH="/home/jonathan/Vulkan/1.2.170.0/x86_64/lib:"
这就是跑步. setup-env.sh
设置他们的原因。
但这似乎很尴尬且不必要地困难,有没有更好的方法来运行脚本并设置永久环境变量?
这很复杂的原因是脚本在它们自己的子 shell 中运行:您当前环境的副本。因此,一旦脚本退出并将您返回到原始 shell,脚本设置的任何变量都会被丢弃。但是,由于能够以这种方式设置变量确实很重要,因此有一个工具可以做到这一点。您正在寻找.
(或source
)命令:
$ help .
.: . filename [arguments]
Execute commands from a file in the current shell.
Read and execute commands from FILENAME in the current shell. The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.
Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.
因此,在您的情况下,如果您希望在当前 shell 中设置该文件中的变量,您可以执行以下操作:
$ . /path/to/setup-env.sh
或者,要为每个 shell 完成它,您可以将此行添加到您的~/.profile
(或者,如果存在,您的/.bash_profile
):
. /path/to/setup-env.sh
您可以将其添加到~/.bashrc
,但这会降低效率,因为它会被您打开的每个新的非登录交互式 shell 读取(这是您在图形 Linux 系统中打开终端时得到的),而~/.profile
只能被读取登录 shell 因此应该在您登录时读取一次,永远不要再读取。现在,~/.profile
当您以图形方式登录时,某些系统不提供源,因此如果您发现它在 中不起作用~/.profile
,请继续将其添加到 中~/.bashrc
。
最后,您可以简化它。没有理由将变量定义和export
命令分开,您可以一步完成:
export VULKAN_SDK="$(dirname "$(readlink -f "${BASH_SOURCE:-$_}" )" )/x86_64"
export PATH="$VULKAN_SDK/bin:$PATH"
export LD_LIBRARY_PATH="$VULKAN_SDK/lib:${LD_LIBRARY_PATH:-}"
export VK_LAYER_PATH="$VULKAN_SDK/etc/vulkan/explicit_layer.d"
进一步阅读:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句