linux 下环境变量设置

这一生的挚爱 提交于 2019-12-29 21:40:21

环境变量PATH

     echo $PATH 查看环境变量的值

 环境变量的设置

     临时设置  可以在终端下

           export  LD_LIBRARY_PATH=./lib:LD_LIBRARY_PATH   用冒号拼接否则覆盖掉之前的值

  永久设置分为在当前用户下还是系统下

       当前用户修改  ~/.bashrc文件  然后保存后执行 source ~/.bashrc

      系统修改 /etc/profile   source /etc/profile

环境变量,是指在操作系统中用来指定操作系统运行环境的一些参数。

通常具备以下特征:
1 字符串(本质) 2 有统一的格式:名=值[:值] 3 值用来描述进程环境信息。
存储形式:与命令行参数类似。char *[]数组,数组名 environ,内部存储字符串,NULL 作为哨兵结尾。
使用形式:与命令行参数类似。
加载位置:与命令行参数类似。位于用户区,高于 stack 的起始位置。
引入环境变量表:须声明环境变量。extern char ** environ;

环境变量就是一个字符串储存在数组environ中,可以循环打印数组environ

#include <stdio.h>
extern char **environ;
int main(void)
{
	int i;
	for(i = 0; environ[i] != NULL; i++){
		printf("%s\n", environ[i]);
	}
	return 0;
}

下面记录几个操作环境变量的系统函数

1、getenv函数    

    获取环境变量的值

char *getenv(const char *name); //成功:返回环境变量的值;失败:NULL (name 不存在)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
extern char **environ;
char *my_getenv(const char *name)
{
	char *p = NULL;
	int i, len;
	for(i = 0; environ[i] != NULL; i++){
		p = strstr(environ[i], "=");
		len = p - environ[i];
		if(strncmp(name, environ[i], len) == 0){
			return p+1;
		}
	}
	return NULL;
}
int main(int argc, char *argv[])
{
	char *p = NULL;
	p = getenv(argv[1]);
	//p = my_getenv(argv[1]);
	if(p == NULL)
		printf("there is no match\n");
	else
		printf("%s\n", p);
	return 0;
}

2、setenv函数

设置环境变量的值

int setenv(const char *name, const char *value, int overwrite);
//成功:0;失败:-1
//参数 overwrite 取值: 1:覆盖原环境变量
//0:不覆盖。(该参数常用于设置新环境变量,如:ABC = haha-day-night)

3、unsetenv 函数

 删除环境变量 name 的定义

int unsetenv(const char *name); 成功:0;失败:-1
//注意事项:name 不存在仍返回 0(成功),当 name 命名为"ABC="时则会出错
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
	char *val;
	const char *name = "ABD";
	val = getenv(name);
	printf("1, %s = %s\n", name, val);
	setenv(name, "haha-day-and-night", 1);
	val = getenv(name);
	printf("2, %s = %s\n", name, val);
#if 1
	int ret = unsetenv("ABD=");
    printf("ret = %d\n", ret);
	val = getenv(name);
	printf("3, %s = %s\n", name, val);
#else
	int ret = unsetenv("ABD");  //name=value:value
	printf("ret = %d\n", ret);
	val = getenv(name);
	printf("3, %s = %s\n", name, val);
#endif
	return 0;
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!