开发者

How do I check if a PATH is set? And if not, set it from an argument

开发者 https://www.devze.com 2023-03-14 17:17 出处:网络
#!/bin/bash if[$LD_PATH == \"\"] then export LD_PATH=$1 else export LD_PATH=$LD_PATH f开发者_StackOverflow中文版i
#!/bin/bash

if[$LD_PATH == ""]
 then
   export LD_PATH=$1
 else
   export LD_PATH=$LD_PATH
f开发者_StackOverflow中文版i

#excute the program that needs the path
./someProgThatNeedsThePath

i keep getting "cannot open shared object file"


First, your bash syntax is broken due to lack of spaces. First, you would need spaces around the [ and ] closures. If you use the newer alternate double bracket syntax, you don't have to worry about quoting variables you are testing.

#!/bin/bash

if [[ $LD_PATH = "" ]]; then
   export LD_PATH="$1"
else
   export LD_PATH="$LD_PATH"
fi

But your real problem is not that at all. Since your code is running in a separate bash shell, the code will have no effect on anything you run in the parent shell. In order to do that you would want to build a function:

function add_to_ld_path () {
    if [[ -z $LD_PATH ]]; then
       export LD_PATH="$1"
    fi
}

Add that code to your .profile, then run it with add_to_ld_path /my/path when you want to use it. Note that since your "else" statement wasn't actually doing anything, I removed it. I also replaced your test for a blank string by making your own with quotes with the builtin empty string test.

Next up is what you are actually trying to accomplish. If all you want to do is set the variable if it's empty, UncleAli's solution is very simple. But it might be useful to do something like this:

function add_to_ld_path () {
    case ":$LD_PATH:" in
      *"$1"*) :;;
      *) LD_PATH=$LD_PATH:$1
    esac
}

This would check the current path and add the path given if it wasn't already part of the LD_PATH variable, otherwise it would leave it alone.


if [ -z "$LD_PATH" ]
then
  export LD_PATH=$1
fi

Will that do the job?

0

精彩评论

暂无评论...
验证码 换一张
取 消