bash nounset 时如何在 shell 中智能附加 LD_LIBRARY_PATH
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9631228/
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
how to smart append LD_LIBRARY_PATH in shell when nounset
提问by Daniel YC Lin
In following shell, error shows LD_LIBRARY_PATH: unbound variableif the LD_LIBRARY_PATH not set.
在以下 shell 中,错误显示LD_LIBRARY_PATH: unbound variable如果 LD_LIBRARY_PATH 未设置。
Can I use similar usage like ${xxx:-yyy} to simplified it.
我可以使用类似 ${xxx:-yyy} 的用法来简化它吗?
#!/bin/bash
set -o nounset
export LD_LIBRARY_PATH=/mypath:$LD_LIBRARY_PATH
回答by Christian.K
You could use this construct:
你可以使用这个结构:
export LD_LIBRARY_PATH=/mypath${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
Explanation:
解释:
If
LD_LIBRARY_PATHis not set, then${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}expands to nothing without evaluating$LD_LIBRARY_PATH, thus the result is equivalent toexport LD_LIBRARY_PATH=/mypathand no error is raised.If
LD_LIBRARY_PATHis already set, then${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}expands to:$LD_LIBRARY_PATH, thus the result is equivalent toexport LD_LIBRARY_PATH=/mypath:$LD_LIBRARY_PATH.
如果
LD_LIBRARY_PATH未设置,则${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}在不评估 的情况下扩展为空$LD_LIBRARY_PATH,因此结果等效于export LD_LIBRARY_PATH=/mypath并且不会引发错误。如果
LD_LIBRARY_PATH已经设置,则${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}扩展为:$LD_LIBRARY_PATH,因此结果等价于export LD_LIBRARY_PATH=/mypath:$LD_LIBRARY_PATH。
See the Bash Reference Manual / 3.5.3 Shell Parameter Expansionfor more information on these expansions.
有关这些扩展的更多信息,请参阅Bash 参考手册/3.5.3 Shell 参数扩展。
This is an important security practice as two adjacent colons or a trailing/leading colon count as adding the current directoryto $PATHor $LD_LIBRARY_PATH. See also:
这是一个重要的安全实践,因为两个相邻的冒号或尾随/前导冒号将当前目录添加到$PATH或$LD_LIBRARY_PATH。也可以看看:

