Argent
Argent

Reputation: 837

Pass Variable Name and Value in Bash Script

I just want to verify that the script I wrote is doing what I think it's doing, and that it's doing it properly.

I wanted to write a script that takes an environment variable and a string value, and then sets that variable to the given value. So I can do something like setvar BOOST_HOME /home/me/boost/boost_1.52.0 and the script will export BOOST_HOME=/home/me/boost/boost_1.52.0

Something like:

#!/bin/bash
# Usage: setvar VAR VAR_VALUE
function setvar()
{
    VAR=${1}
    VAR_VALUE=${2}
    if [ -d $2 ]
    then
        eval export $VAR=$2
    fi
}

This seems to work, at least judging from a echo echo tests, but I am still not very comfortable with shell scripting, and would like someone to either verify what I am doing or point out what I am doing wrong / less correct.

Upvotes: 1

Views: 1411

Answers (1)

rici
rici

Reputation: 241931

You don't need the eval.

setvar() {
  if [[ -d $2 ]]; then
    export "$1=$2"
  fi
}

Using [[ instead of [ avoids the need to quote $2, since the bash (and other shell) extension [[ does not word-split interior parameter expansions. If I'd stuck with the old-fashioned [ -d "$2" ], I would have had to quote the $2 in case its value included whitespace.

Upvotes: 5

Related Questions