Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to smart append LD_LIBRARY_PATH in shell when nounset

Tags:

bash

shell

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 it.

#!/bin/bash set -o nounset export LD_LIBRARY_PATH=/mypath:$LD_LIBRARY_PATH 
like image 770
Daniel YC Lin Avatar asked Mar 09 '12 08:03

Daniel YC Lin


People also ask

How do I set LD_LIBRARY_PATH?

In your terminal, type the following sudo ldconfig and press enter on your keyboard. Close all your open terminals that you were using then open a new terminal session and run echo $LD_LIBRARY_PATH If you see the path you added is echoed back, you did it right.

What does export LD_LIBRARY_PATH do?

LD_LIBRARY_PATH is an environmental variable used in Linux/UNIX Systems. It is used to tell dynamic link loaders where to look for shared libraries for specific applications. It is useful until you don't mess with it.

Does LD_LIBRARY_PATH search recursively?

No, elements of LD_LIBRARY_PATH are not searched recursively.

What should be in LD_LIBRARY_PATH?

Set the LD_LIBRARY_PATH to include the directory or directories that contain your libraries.


1 Answers

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
like image 187
Christian.K Avatar answered Sep 28 '22 10:09

Christian.K