search
HomeOperation and MaintenanceLinux Operation and Maintenance6 ways to configure Linux environment variables, recommended to collect!

This article brings you six methods of configuring environment variables in Linux. I hope it will be helpful to you.

6 ways to configure Linux environment variables, recommended to collect!

Linux environment variable configuration

When customizing software installation, it is often necessary to configure environment variables , various configuration methods for environment variables are listed below.

The environment description of all the examples below is as follows:

System: Ubuntu 14.0

User name: uusama

Need to configure the MySQL environment variable path:/home/ uusama/mysql/bin

Linux reading environment variables

How to read environment variables:

  • The export command displays all environment variables defined by the current system

  • echo $PATH command outputs the value of the current PATH environment variable

This The effect of executing the two commands is as follows

uusama@ubuntu:~export
declare -x HOME="/home/uusama"
declare -x LANG="en_US.UTF-8"
declare -x LANGUAGE="en_US:"
declare -x LESSCLOSE="/usr/bin/lesspipe %s %s"
declare -x LESSOPEN="| /usr/bin/lesspipe %s"
declare -x LOGNAME="uusama"
declare -x MAIL="/var/mail/uusama"
declare -x PATH="/home/uusama/bin:/home/uusama/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
declare -x SSH_TTY="/dev/pts/0"
declare -x TERM="xterm"
declare -x USER="uusama"
uusama@ubuntu:~ echo $PATH
/home/uusama/bin:/home/uusama/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

The PATH variable defines the search path for running the command. Different paths are separated by colon:. When using export definition, you can add double quotes or not.

Linux environment variable configuration method one: export PATH

Use the export command to directly modify the value of PATH and configure MySQL to enter the environment variable:

export PATH=/home/uusama/mysql/bin:PATH
# 或者把PATH放在前面
export PATH=PATH:/home/uusama/mysql/bin

Notes:

Effective time: effective immediately

Effective period: valid for the current terminal, invalid after the window is closed

Effective range: only for the current time Don’t forget to add the original configuration, that is, the $PATH part, to the user’s valid

configured environment variables to avoid overwriting the original configuration

Linux environment variable configuration method two: vim ~/.bashrc

Configure by modifying the ~/.bashrc file in the user directory:

vim ~/.bashrc
# 在最后一行加上
export PATH=$PATH:/home/uusama/mysql/bin

Notes:

Effective time: It will take effect when opening a new terminal with the same user, or manually source ~/.bashrc

Effectiveness period: valid forever

Validity range: valid only for the current user

If subsequent environment variable loading files overwrite the PATH definition, it may not take effect

Linux environment variable configuration method three: vim ~/.bash_profile

Similar to modifying the ~/.bashrc file, you also need to add the new path at the end of the file:

vim ~/.bash_profile
# 在最后一行加上
export PATH=$PATH:/home/uusama/mysql/bin

Notes:

Effective time: Use the same user to open a new It takes effect when using the terminal, or manually source /.bash_profile to take effect

Effectiveness period: permanently valid

Effectiveness scope: only valid for the current user

If there is no /.bash_profile file, Then you can edit the ~/.profile file or create a new

Linux environment variable configuration method four: vim /etc/bashrc

This method is Modifying the system configuration requires administrator rights (such as root) or write permission to the file:

# 如果/etc/bashrc文件不可编辑,需要修改为可编辑
chmod -v u+w /etc/bashrc
vim /etc/bashrc
# 在最后一行加上
export PATH=$PATH:/home/uusama/mysql/bin

Notes:

Effective time: Open a new terminal to take effect, or manually source /etc /bashrc takes effect

Effectiveness period: permanently valid

Validity scope: valid for all users

Linux environment variable configuration method five: vim /etc/ profile

This method modifies the system configuration and requires administrator rights or write permissions to the file. It is similar to vim /etc/bashrc:

# 如果/etc/profile文件不可编辑,需要修改为可编辑
chmod -v u+w /etc/profile
vim /etc/profile
# 在最后一行加上
export PATH=$PATH:/home/uusama/mysql/bin

Notes:

Effective time: Take effect when opening a new terminal, or manually source /etc/profile

Effectiveness period: Permanent

Effectiveness scope: Valid for all users

Linux environment variable configuration method six: vim /etc/environment

This method is to modify the system environment configuration file, which requires administrator rights or permission to the file. Write permission:

# 如果/etc/bashrc文件不可编辑,需要修改为可编辑
chmod -v u+w /etc/environment
vim /etc/profile
# 在最后一行加上
export PATH=$PATH:/home/uusama/mysql/bin注意事项:

Effective time: Take effect when opening a new terminal, or manually source /etc/environment

Effective period: Permanent

Effective scope: For all users Effective

Linux environment variable loading principle analysis

The various configuration methods of environment variables are listed above, so how does Linux load these configurations? What about? In what order are they loaded?

Specific loading order will cause environment variable definitions with the same name to be overwritten or not take effect.

Classification of environment variables

Environment variables can be simply divided into user-defined environment variables and system-level environment variables.

User-level environment variable definition files: /.bashrc, /.profile (some systems are: /.bash_profile)

System-level environment variable definition files: /etc/bashrc, /etc/ profile (some systems are: /etc/bash_profile), /etc/environment

In addition, in the user environment variables, the system will first read the /.bash_profile (or ~/.profile) file. If there is no such file Then read ~/.bash_login, and then read ~/.bashrc based on the contents of these files.

How to test the loading order of Linux environment variables

为了测试各个不同文件的环境变量加载顺序,我们在每个环境变量定义文件中的第一行都定义相同的环境变量UU_ORDER,该变量的值为本身的值连接上当前文件名称。

需要修改的文件如下:

  • /etc/environment

  • /etc/profile

  • /etc/profile.d/test.sh,新建文件,没有文件夹可略过

  • /etc/bashrc,或者/etc/bash.bashrc

  • /.bash_profile,或者/.profile

  • ~/.bashrc

在每个文件中的第一行都加上下面这句代码,并相应的把冒号后的内容修改为当前文件的绝对文件名。

export UU_ORDER="$UU_ORDER:~/.bash_profile"

修改完之后保存,新开一个窗口,然后echo $UU_ORDER观察变量的值:

uusama@ubuntu:~echoUU_ORDER
$UU_ORDER:/etc/environment:/etc/profile:/etc/bash.bashrc:/etc/profile.d/test.sh:~/.profile:~/.bashrc

可以推测出Linux加载环境变量的顺序如下:

/etc/environment

/etc/profile

/etc/bash.bashrc

/etc/profile.d/test.sh

~/.profile

~/.bashrc

Linux环境变量文件加载详解

由上面的测试可容易得出Linux加载环境变量的顺序如下,:

系统环境变量 -> 用户自定义环境变量 /etc/environment -> /etc/profile -> ~/.profile

打开/etc/profile文件你会发现,该文件的代码中会加载/etc/bash.bashrc文件,然后检查/etc/profile.d/目录下的.sh文件并加载。

# /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

其次再打开~/.profile文件,会发现该文件中加载了~/.bashrc文件。

# 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 directories
PATH="HOME/bin:HOME/.local/bin:PATH"

从~/.profile文件中代码不难发现,/.profile文件只在用户登录的时候读取一次,而/.bashrc会在每次运行Shell脚本的时候读取一次。

一些小技巧

可以自定义一个环境变量文件,比如在某个项目下定义uusama.profile,在这个文件中使用export定义一系列变量,然后在~/.profile文件后面加上:sourc uusama.profile,这样你每次登陆都可以在Shell脚本中使用自己定义的一系列变量。

也可以使用alias命令定义一些命令的别名,比如alias rm="rm -i"(双引号必须),并把这个代码加入到~/.profile中,这样你每次使用rm命令的时候,都相当于使用rm -i命令,非常方便。

相关推荐:《Linux视频教程

The above is the detailed content of 6 ways to configure Linux environment variables, recommended to collect!. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金. If there is any infringement, please contact admin@php.cn delete
Linux Operations: Utilizing the Maintenance ModeLinux Operations: Utilizing the Maintenance ModeApr 19, 2025 am 12:08 AM

Linux maintenance mode can be entered through the GRUB menu. The specific steps are: 1) Select the kernel in the GRUB menu and press 'e' to edit, 2) Add 'single' or '1' at the end of the 'linux' line, 3) Press Ctrl X to start. Maintenance mode provides a secure environment for tasks such as system repair, password reset and system upgrade.

Linux: How to Enter Recovery Mode (and Maintenance)Linux: How to Enter Recovery Mode (and Maintenance)Apr 18, 2025 am 12:05 AM

The steps to enter Linux recovery mode are: 1. Restart the system and press the specific key to enter the GRUB menu; 2. Select the option with (recoverymode); 3. Select the operation in the recovery mode menu, such as fsck or root. Recovery mode allows you to start the system in single-user mode, perform file system checks and repairs, edit configuration files, and other operations to help solve system problems.

Linux's Essential Components: Explained for BeginnersLinux's Essential Components: Explained for BeginnersApr 17, 2025 am 12:08 AM

The core components of Linux include the kernel, file system, shell and common tools. 1. The kernel manages hardware resources and provides basic services. 2. The file system organizes and stores data. 3. Shell is the interface for users to interact with the system. 4. Common tools help complete daily tasks.

Linux: A Look at Its Fundamental StructureLinux: A Look at Its Fundamental StructureApr 16, 2025 am 12:01 AM

The basic structure of Linux includes the kernel, file system, and shell. 1) Kernel management hardware resources and use uname-r to view the version. 2) The EXT4 file system supports large files and logs and is created using mkfs.ext4. 3) Shell provides command line interaction such as Bash, and lists files using ls-l.

Linux Operations: System Administration and MaintenanceLinux Operations: System Administration and MaintenanceApr 15, 2025 am 12:10 AM

The key steps in Linux system management and maintenance include: 1) Master the basic knowledge, such as file system structure and user management; 2) Carry out system monitoring and resource management, use top, htop and other tools; 3) Use system logs to troubleshoot, use journalctl and other tools; 4) Write automated scripts and task scheduling, use cron tools; 5) implement security management and protection, configure firewalls through iptables; 6) Carry out performance optimization and best practices, adjust kernel parameters and develop good habits.

Understanding Linux's Maintenance Mode: The EssentialsUnderstanding Linux's Maintenance Mode: The EssentialsApr 14, 2025 am 12:04 AM

Linux maintenance mode is entered by adding init=/bin/bash or single parameters at startup. 1. Enter maintenance mode: Edit the GRUB menu and add startup parameters. 2. Remount the file system to read and write mode: mount-oremount,rw/. 3. Repair the file system: Use the fsck command, such as fsck/dev/sda1. 4. Back up the data and operate with caution to avoid data loss.

How Debian improves Hadoop data processing speedHow Debian improves Hadoop data processing speedApr 13, 2025 am 11:54 AM

This article discusses how to improve Hadoop data processing efficiency on Debian systems. Optimization strategies cover hardware upgrades, operating system parameter adjustments, Hadoop configuration modifications, and the use of efficient algorithms and tools. 1. Hardware resource strengthening ensures that all nodes have consistent hardware configurations, especially paying attention to CPU, memory and network equipment performance. Choosing high-performance hardware components is essential to improve overall processing speed. 2. Operating system tunes file descriptors and network connections: Modify the /etc/security/limits.conf file to increase the upper limit of file descriptors and network connections allowed to be opened at the same time by the system. JVM parameter adjustment: Adjust in hadoop-env.sh file

How to learn Debian syslogHow to learn Debian syslogApr 13, 2025 am 11:51 AM

This guide will guide you to learn how to use Syslog in Debian systems. Syslog is a key service in Linux systems for logging system and application log messages. It helps administrators monitor and analyze system activity to quickly identify and resolve problems. 1. Basic knowledge of Syslog The core functions of Syslog include: centrally collecting and managing log messages; supporting multiple log output formats and target locations (such as files or networks); providing real-time log viewing and filtering functions. 2. Install and configure Syslog (using Rsyslog) The Debian system uses Rsyslog by default. You can install it with the following command: sudoaptupdatesud

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)