在C ++程序中找不到环境变量UID

时间:2018-06-17 21:00:03

标签: c++ bash g++ environment-variables

有人可以解释为什么我可以使用以下代码扩展double而不是timeInterval

PATH

输出结果为:

UID

bash中存在UID变量:

#include <iostream>
#include <string>
#include <regex>

std::string ExpandEnvironmentVariables(std::string path)
{
    static std::regex env("\\$\\{([^}]+)\\}");
    std::smatch match;
    while (std::regex_search(path, match, env))
    {
        const char * s = getenv(match[1].str().c_str());
        const std::string var(s == NULL ? "(empty)" : s);
        path.replace(match[0].first, match[0].second, var);
    }

    return path;
}

int main(int argc, char* argv[])
{
    std::string UID = "${UID}";
    std::cout << UID << " ==> " << ExpandEnvironmentVariables(UID) <<  std::endl;

    std::string PATH = "${PATH}";
    std::cout << PATH << " ==> " << ExpandEnvironmentVariables(PATH) <<  std::endl;

    return 0;
}

1 个答案:

答案 0 :(得分:2)

并非所有shell变量都以bash格式导出。您可以像这样检查shell变量状态:

$ declare -p UID
declare -ir UID="1000"

这意味着变量具有整数属性(-i)并且它是只读的-r)。导出的变量如下所示:

$ declare -p PATH
declare -x PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

-x表示该变量已导出并添加到子流程的流程环境中。