如何使用 setenv 在 bash 中设置环境变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5382586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:38:49  来源:igfitidea点击:

How can I set environmental variables in bash using setenv?

bashtcshsetenv

提问by Santhana Kumar

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

我有一个文件,其中包含以以下格式运行的应用程序所需的所有环境变量...

setenv DISPLAY [email protected]
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 setenvcommand in bash?

我将如何设置 env. bash 中的变量使用上述文件?有没有办法setenv在 bash 中以某种方式使用命令?

回答by Eugene Yarmash

You can define a function named setenv:

您可以定义一个名为 的函数setenv

function setenv() { export "="; }

To set the envariables, source the file:

要设置 envariables,请获取文件:

. your_file

回答by Nordl?w

This is an improved version.

这是一个改进的版本。

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

回答by Peter John Acklam

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

这是 ksh/bash 的更完整版本。无论参数的数量如何,它的行为都类似于 csh/tcsh setenv。

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

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

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