stackoverflow
stackoverflow

Reputation: 19474

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

#!/bin/bash

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

#excute the program that needs the path
./someProgThatNeedsThePath

i keep getting "cannot open shared object file"

Upvotes: 1

Views: 1940

Answers (2)

Caleb
Caleb

Reputation: 5438

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.

Upvotes: 8

UncleAli
UncleAli

Reputation: 505

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

Will that do the job?

Upvotes: 2

Related Questions