how to smart append LD_LIBRARY_PATH in shell when nounset

前端 未结 1 535
借酒劲吻你
借酒劲吻你 2021-01-30 17:54

In following shell, error shows LD_LIBRARY_PATH: unbound variable if the LD_LIBRARY_PATH not set.

Can I use similar usage like ${xxx:-yyy} to simplified

相关标签:
1条回答
  • 2021-01-30 18:18

    You could use this construct:

    export LD_LIBRARY_PATH=/mypath${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
    

    Explanation:

    • If LD_LIBRARY_PATH is not set, then ${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} expands to nothing without evaluating $LD_LIBRARY_PATH, thus the result is equivalent to export LD_LIBRARY_PATH=/mypath and no error is raised.

    • If LD_LIBRARY_PATH is already set, then ${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH} expands to :$LD_LIBRARY_PATH, thus the result is equivalent to export LD_LIBRARY_PATH=/mypath:$LD_LIBRARY_PATH.

    See the Bash Reference Manual / 3.5.3 Shell Parameter Expansion for more information on these expansions.

    This is an important security practice as two adjacent colons or a trailing/leading colon count as adding the current directory to $PATH or $LD_LIBRARY_PATH. See also:

    • What corner cases must we consider when parsing path on linux
    • bash: $PATH ending in colon puts working directory in PATH
    • How Torch broke ls
    0 讨论(0)
提交回复
热议问题