4

I've a file containing all the environmental variables needed for an application to run in the following format...

setenv DISPLAY invest7@example.com
setenv HOST example.com
setenv HOSTNAME sk
...

How would I set the env. variables in bash using the above file? Is there a way to somehow use setenv command in bash?

arserbin3
  • 6,010
  • 8
  • 36
  • 52

3 Answers3

6

You can define a function named setenv:

function setenv() { export "$1=$2"; }

To set the envariables, source the file:

. your_file
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
1

This is an improved version.

# Mimic csh/tsch setenv
function setenv()
{
    if [ $# = 2 ]; then
        export $1=$2;
    else
        echo "Usage: setenv [NAME] [VALUE]";
    fi
}
navid
  • 566
  • 6
  • 15
Nordlöw
  • 11,838
  • 10
  • 52
  • 99
0

Here is a more complete version for ksh/bash. It behaves like csh/tcsh setenv regardless of the number of arguments.

setenv () {
    if (( $# == 0 )); then
        env
        return 0
    fi

    if [[ $1 == *[!A-Za-z0-9_]* ]]; then
        printf 'setenv: not a valid identifier -- %s\n' "$1" >&2
        return 1
    fi

    case $# in
        1)
            export "$1"
            ;;
        2)
            export "$1=$2"
            ;;
        *)
            printf 'Usage: setenv [VARIABLE [VALUE]]\n' >&2
            return 1
    esac
}