设备环境

WSL2

Ubuntu-20.04

本教程适配所有linux,不管你是虚拟机还是WSL或者其他的平台。

问题阐述

由于专业课的要求,需要在Linux中新建一个用户,然后转到这个用户来完成专业课的各种实践要求。有可能是我在新建用户后没有执行某个”特定”的配置,导致我遇到个人的环境变量配置不能自动加载的问题,其实我一步一步按照安装手册进行了相应操作。

我详细介绍一下我的问题:

可以看到我新建的用户为hadoop,但是明眼人一下就会发现,为什么换了一个用户,用户名的颜色就变了,一个绿色,非常醒目好看,而一个浅色,显得那么苍白。其实这也为后面埋下了伏笔。

image-20231011144535656

我通过sudo vim ~/.bashrc来查看环境变量,如下:
image-20231011145229904

可以看到关于java的环境变量我已配置,但是我在终端执行java -version后却弹出没有找到该命令的问题:
image-20231011145419897

我使用source ~/.profile命令来刷新配置文件,可以看到用户名变为了绿色,并且java -version也能够成功使用,我以为我成功了。

image-20231011145544625

如果你没有profile文件,就通过sudo vim ~/.profile新建一个,并把下列代码添加进去:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# ~/.profile: executed by the command interpreter for login shells.
# This file is not read by bash(1), if ~/.bash_profile or ~/.bash_login
# exists.
# see /usr/share/doc/bash/examples/startup-files for examples.
# the files are located in the bash-doc package.

# the default umask is set in /etc/profile; for setting the umask
# for ssh logins, install and configure the libpam-umask package.
#umask 022

# if running bash
if [ -n "$BASH_VERSION" ]; then
# include .bashrc if it exists
if [ -f "$HOME/.bashrc" ]; then
. "$HOME/.bashrc"
fi
fi

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
PATH="$HOME/bin:$PATH"
fi

# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/.local/bin" ] ; then
PATH="$HOME/.local/bin:$PATH"
fi

可是当我退出linux系统重新登录后,用户名又变为白色,并且java -version也不能使用,人崩了,虽然可以继续执行source ~/.profile来重新加载配置文件,但是你想如果每次登录linux这个用户都要执行刷新命令,那该多鸡肋啊,而且这也不符合程序员的规范啊,是我我就受不了。

解决方法

编辑bash_profile文件,使得终端每次启动能够自动加载个人配置文件。

解释:.bash_profile 文件,这个文件只在登录shell启动时被读取。如果你想让终端启动时自动刷新个人配置文件,你需要在 .bash_profile 文件中添加一行命令来读取 .bashrc 文件。

执行sudo vim ~/.bash_profile命令(如果没有该文件,会自动创建),加入以下代码:

1
2
3
if [ -f ~/.bashrc ]; then
source ~/.bashrc
fi

这段代码的意思是,如果 .bashrc 文件存在,那么就执行 source ~/.bashrc 命令来读取它。

image-20231011151551926

最后,你需要让修改后的 .bash_profile 文件立即生效。在终端中输入 source ~/.bash_profile 即可。

我们可以看到,用户名又变为了绿色,java -version命令也能够正常使用。image-20231011151843399

并且当你退出该终端,重新登录该用户,可以看到用户名一开始就是绿色,java -version命令也能够使用。Cheers!

image-20231011152044702

至此linux终端启动后不能自动加载环境变量配置的问题已经完美解决,好了,我要去肝专业课的实验了🤣。