Linux环境变量配置文件
笔者最近在配置服务器环境,第一次仔细琢磨了一下Linux的几个环境变量配置文件,遂(以Ubuntu22.04为例)写下这一篇博客:
Linux环境变量
在自定义安装软件的时候,经常需要配置环境变量:
export
命令显示当前系统定义的所有环境变量echo $PATH
命令输出当前的PATH
环境变量的值
Linux环境变量配置方法一:export PATH
使用export
命令直接修改PATH
的值,使用该方法立即生效,但只在当前终端有效,切换终端后即失效,配置的环境变量中不要忘了加上原来的配置,即$PATH
部分,避免覆盖原来配置。
Linux环境变量配置方法二:修改配置文件
环境变量配置文件有:/etc/profile
, /etc/bash.bashrc
, /etc/profile.d/*
, ~/.bashrc
, ~/.profile
/etc/profile
:为系统的每个用户设置环境信息,当用户第一次登录(login shell)时,该文件被执行
# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).
if [ "${
PS1-}" ]; then
if [ "${
BASH-}" ] && [ "$BASH" != "/bin/sh" ]; then
# The file bash.bashrc already sets the default PS1.
# PS1='\h:\w\$ '
if [ -f /etc/bash.bashrc ]; then
. /etc/bash.bashrc
fi
else
if [ "$(id -u)" -eq 0 ]; then
PS1='# '
else
PS1='$ '
fi
fi
fi
if [ -d /etc/profile.d ]; then
for i in /etc/profile.d/*.sh; do
if [ -r $i ]; then
. $i
fi
done
unset i
fi
我们可以观察到Ubuntu22.04的默认/etc/profile
会首先执行/etc/bash.bashrc
,之后判断是否为root
用户,来确定终端提示符是$
或 #
,最后逐个执行/etc/profile.d/
中的所有脚本
由于 /etc/profile
只会在登录时自动执行,因此我们在自动切换用户的时候要注意手动执行source /etc/profile
/etc/profile.d
:目录中存放的是一些应用程序所需的启动脚本,而这些脚本文件是用来设置一些变量和运行一些初始化过程的。其中包括了颜色、语言、less、vim及which等命令的一些附加设置,其是由/etc/profile
调用的,因此也仅在登录时启用。/etc/profile.d/ 比 /etc/profile 好维护。不想要什么变量直接删除/etc/profile.d/下对应的.sh 的shell脚本即可,不用像/etc/profile需要改动此文件。
(base) ubuntu@VM-4-15-ubuntu:~$ ls /etc/profile.d/
01-locale-fix.sh bash_completion.sh gawk.sh Z97-byobu.sh Z99-cloud-locale-test.sh
apps-bin-path.sh gawk.csh qcloud.sh Z99-cloudinit-warnings.sh
/etc/bash.bashrc
:为每一个运行bash shell的用户执行此文件,当bash shell被打开时,该文件被读取。
# System-wide .bashrc file for interactive bash(1) shells.
# To enable the settings / commands in this file for login shells as well,
# this file has to be sourced in /etc/profile.
# If not running interactively, don't do anything
[ -z "$PS1" ] && return
# check the window size after each command and, if necessary,
# update the values of LINES and COLUMNS.
shopt -s checkwinsize
# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then<