🌈前言
本篇文章进行操作系统中环境变量的学习!!!
🌷1、概念和操作
-
环境变量(environment variables)一般是指在操作系统中用来指定操作系统运行环境的一些参数
-
如:我们在编写C/C++代码的时候,在链接的时候,从来不知道我们的所链接的动态静态库在哪里,但是照样可以链接成功,生成可执行程序,原因就是有相关环境变量帮助编译器进行查找
-
环境变量通常具有某些特殊用途,还有在系统当中通常具有全局特性
环境变量分为二种:用户变量(局部变量)和系统变量(全局变量)
- 通过直接命令行定义变量可以生成”用户变量“
- 使用export指令创建系统变量
🌹2、环境变量相关指令
- echo:显示某个环境变量值
- expor:设置一个新的环境变量
- env:显示所有环境变量
- unset:清除环境变量
- set:显示本地定义的shell变量和环境变量
为什么指令可以直接运行,程序要加上路径(./ + 可执行文件)呢?
- 指令和安装的软件脚本一般都是存储在【/usr/bin】可执行二进制文件的目录下
// 直接通过指令运行
[lyh_sky@localhost lesson11]$ ls
makefile test test.cpp
// 通过/usr/bin/运行
[lyh_sky@localhost lesson11]$ /usr/bin/ls
makefile test test.cpp
[lyh_sky@localhost lesson11]$ cat test.cpp
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
using namespace std;
int main()
{
while (1)
{
cout << "hello world!!!" << endl;
sleep(1);
}
return 0;
}
// 通过指令方式运行失败
[lyh_sky@localhost lesson11]$ test
bash: test: 未找到命令... // 执行一个可执行程序,必须先找到它
// 加上路径运行成功
[lyh_sky@localhost lesson11]$ ./test
hello world!!!
hello world!!!
....
- 系统中存在相关的环境变量,是保存了程序的搜索路径的!!!
-
在OS中,搜索可执行程序路径的环境变量是”PATH“!!!
-
OS是通过PATH环境变量里面的路径来搜索指令(可执行程序)的,该环境变量用冒号分隔路径
-
可以使用env指令查看OS中的全部环境变量
-
还可以使用echo 【$环境变量】来显示指定环境变量的值
如何将自己写的程序也能像指令一样不用带路径执行呢?
- 方法一:将当前工作路径中的可执行文件拷贝到/usr/bin/目录中
[lyh_sky@localhost lesson11]$ ls
makefile tes test.cpp
[lyh_sky@localhost lesson11]$ tes
bash: tes: 未找到命令...
[lyh_sky@localhost lesson11]$ sudo cp tes /usr/bin/
[lyh_sky@localhost lesson11]$ ls /usr/bin/tes
/usr/bin/tes
[lyh_sky@localhost lesson11]$ tes
hello world!!!
hello world!!!
...
2.方法二:将当前路径添加到PATH环境变量中
[lyh_sky@localhost lesson11]$ ls
makefile tes test.cpp
[lyh_sky@localhost lesson11]$ tes
bash: /usr/bin/tes: 没有那个文件或目录
[lyh_sky@localhost lesson11]$ pwd