开发者

How can I set environmental variables in bash using setenv?

开发者 https://www.devze.com 2023-02-18 15:48 出处:网络
I\'ve a file containing all the environmental variables needed for an applica开发者_如何学Pythontion to run in the following format...

I've a file containing all the environmental variables needed for an applica开发者_如何学Pythontion 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?


You can define a function named setenv:

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

To set the envariables, source the file:

. your_file


This is an improved version.

# Mimic csh/tsch setenv
function setenv()
{
    if [ $# = 2 ]; then
        export $1=$2;
    else
        echo "Usage: setenv [NAME] [VALUE]";
    fi
}


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
}
0

精彩评论

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