【Linux】Linux环境变量

Linux环境变量

​ Linux系统中输入命令后系统调用的方式

Linux 命令位置的查询方式
1. 绝对路径
2. alias别名
3. 内部命令
4. 外部命令 (环境变量的$PATH)

1、查看环境变量

  1. env命令查看所有环境变量

    ubuntu@ubuntu:~$ env
    SHELL=/bin/bash
    SESSION_MANAGER=local/ubuntu:@/tmp/.ICE-unix/1710,unix/ubuntu:/tmp/.
    ICE-unix/1710
    QT_ACCESSIBILITY=1
    COLORTERM=truecolor
    XDG_CONFIG_DIRS=/etc
    
  2. env | grep命令查看指定环境变量

    env | grep PATH
    
    ubuntu@ubuntu:~$ env | grep PATH
    PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/snap/bin
    
  3. echo命令

    ubuntu@ubuntu:~$ echo $PATH
    /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/snap/bin
    

2、编辑环境变量

​ 在Shell下,用export设置的环境变量对当前Shell立即生效,Shell退出后失效。在脚本文件中设置的环境变量不会立即生效,退出Shell后重新登录时才生效,或者用source命令让它立即生效。

2.1 临时环境变量

​ 使用export设置的环境变量在退出shell后就会失效。如果希望永久生效,则需要在登录脚本中设置。

# 设置环境变量值(方法一)
PATH=$PATH:~/local/bin/mytest
export PATH
# 设置环境变量值(方法二)
# 如果环境变量的值没有空格等特殊符号,可以不用单引号包含
export PATH=$PATH:~/local/bin/mytest
export MYENV='~/local/Myenv'
# 删除环境变量 unset $环境变量名
unset $MYENV

2.2 系统环境变量

​ 系统环境变量对全部的用户都生效。

​ 在脚本文件中设置的环境变量不会立即生效,退出Shell后重新登录时才生效,或者用source命令让它立即生效

  1. 方法一:/etc/profile文件中设置环境变量**(不推荐)**

    原理:用户登录时会执行/etc/profile文件,从而通过文件的命令加载环境变量。

    # 文件中添加环境变量的配置(export 环境变量名='环境变量值')
    export PATH=$PATH:~/local/bin/mytest
    export MYENV='~/local/Myenv'
    
    # 以下是原始/etc/profile文件的内容
    
    # /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
    
  2. 方法二/etc/profile.d文件夹目录中增加环境变量脚本文件**(推荐)**

    原理/etc/profile在每次启动中都会执行/etc/profile.d下的全部脚本文件。

    /etc/profile.d/etc/profile更好维护,维护直接修改对应的文件即可。

    # `/etc/profile.d`文件夹目录的默认文件
    ubuntu@ubuntu:/etc/profile.d$ ls
    01-locale-fix.sh       debuginfod.csh            vte-2.91.sh
    apps-bin-path.sh       debuginfod.sh             vte.csh
    bash_completion.sh     gnome-session_gnomerc.sh  xdg_dirs_desktop_session.sh
    cedilla-portuguese.sh  im-config_wayland.sh
    
    # 创建全局环境变量,创建.sh脚本文件后编辑export脚本(编辑过程省略)
    ubuntu@ubuntu:/etc/profile.d$ touch Myenv.sh
    # 查看脚本文件内容
    ubuntu@ubuntu:~/Desktop$ cat Myenv.sh
    export PATH=$PATH:~/local/bin/mytest
    export MYENV='~/local/Myenv'
    
  3. 方法三:/etc/bashrc/etc/bash.bashrc 文件中设置环境变量**(不推荐)**

    原理/etc/profile在每次启动中都会执行``/etc/bashrc/etc/bash.bashrc 文件。

    在 Ubuntu 系统中,全局 Bash 配置位于 /etc/bash.bashrc 文件中

    该文件配置的环境变量会影响用户全部所使用的bash shell

    # 文件中添加环境变量的配置(export 环境变量名='环境变量值')
    export PATH=$PATH:~/local/bin/mytest
    export MYENV='~/local/Myenv'
    
    # 以下是原始/etc/bash.bashrc文件的内容
    
    # 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
        debian_chroot=$(cat /etc/debian_chroot)
    fi
    
    # set a fancy prompt (non-color, overwrite the one in /etc/profile)
    # but only if not SUDOing and have SUDO_PS1 set; then assume smart user.
    if ! [ -n "${SUDO_USER}" -a -n "${SUDO_PS1}" ]; then
      PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
    fi
    
    # Commented out, don't overwrite xterm -T "title" -n "icontitle" by default.
    # If this is an xterm set the title to user@host:dir
    #case "$TERM" in
    #xterm*|rxvt*)
    #    PROMPT_COMMAND='echo -ne "\033]0;${USER}@${HOSTNAME}: ${PWD}\007"'
    #    ;;
    #*)
    #    ;;
    #esac
    
    # enable bash completion in interactive shells
    #if ! shopt -oq posix; then
    #  if [ -f /usr/share/bash-completion/bash_completion ]; then
    #    . /usr/share/bash-completion/bash_completion
    #  elif [ -f /etc/bash_completion ]; then
    #    . /etc/bash_completion
    #  fi
    #fi
    
    # sudo hint
    if [ ! -e "$HOME/.sudo_as_admin_successful" ] && [ ! -e "$HOME/.hushlogin" ] ; then
        case " $(groups) " in *\ admin\ *|*\ sudo\ *)
        if [ -x /usr/bin/sudo ]; then
    	cat <<-EOF
    	To run a command as administrator (user "root"), use "sudo <command>".
    	See "man sudo_root" for details.
    	
    	EOF
        fi
        esac
    fi
    
    # if the command-not-found package is installed, use it
    if [ -x /usr/lib/command-not-found -o -x /usr/share/command-not-found/command-not-found ]; then
    	function command_not_found_handle {
    	        # check because c-n-f could've been removed in the meantime
                    if [ -x /usr/lib/command-not-found ]; then
    		   /usr/lib/command-not-found -- "$1"
                       return $?
                    elif [ -x /usr/share/command-not-found/command-not-found ]; then
    		   /usr/share/command-not-found/command-not-found -- "$1"
                       return $?
    		else
    		   printf "%s: command not found\n" "$1" >&2
    		   return 127
    		fi
    	}
    fi
    

2.3 用户环境变量

​ 用户环境变量只对当前用户有效。

​ 在脚本文件中设置的环境变量不会立即生效,退出Shell后重新登录时才生效,或者用source命令让它立即生效

  1. 方法一:用户主目录下~/.bash_profile文件,Ubuntu 中使用~/.profile 文件中设置环境变量**(推荐)**

    原理:该文件会在用户登录时执行,每个用户都可以使用自己专属的环境变量

    # 文件中添加环境变量的配置(export 环境变量名='环境变量值')
    export PATH=$PATH:~/local/bin/mytest
    export MYENV='~/local/Myenv'
    
    # 以下是原始~/.profile文件的内容
    
    # ~/.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
    
  2. 方法二:用户主目录下~/.bashrc文件中设置环境变量**(不推荐)**

    原理:用户登录和打开Shell时都会读取该文件,每打开一次Shell,文件都会被读取一次。

    # 文件中添加环境变量的配置(export 环境变量名='环境变量值')
    export PATH=$PATH:~/local/bin/mytest
    export MYENV='~/local/Myenv'
    
    # 以下是原始~/.bashrc文件的内容
    
    # ~/.bashrc: executed by bash(1) for non-login shells.
    # see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
    # for examples
    
    # If not running interactively, don't do anything
    case $- in
        *i*) ;;
          *) return;;
    esac
    
    # don't put duplicate lines or lines starting with space in the history.
    # See bash(1) for more options
    HISTCONTROL=ignoreboth
    
    # append to the history file, don't overwrite it
    shopt -s histappend
    
    # for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
    HISTSIZE=1000
    HISTFILESIZE=2000
    
    # check the window size after each command and, if necessary,
    # update the values of LINES and COLUMNS.
    shopt -s checkwinsize
    
    # If set, the pattern "**" used in a pathname expansion context will
    # match all files and zero or more directories and subdirectories.
    #shopt -s globstar
    
    # make less more friendly for non-text input files, see lesspipe(1)
    [ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
    
    # set variable identifying the chroot you work in (used in the prompt below)
    if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
        debian_chroot=$(cat /etc/debian_chroot)
    fi
    
    # set a fancy prompt (non-color, unless we know we "want" color)
    case "$TERM" in
        xterm-color|*-256color) color_prompt=yes;;
    esac
    
    # uncomment for a colored prompt, if the terminal has the capability; turned
    # off by default to not distract the user: the focus in a terminal window
    # should be on the output of commands, not on the prompt
    #force_color_prompt=yes
    
    if [ -n "$force_color_prompt" ]; then
        if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
    	# We have color support; assume it's compliant with Ecma-48
    	# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
    	# a case would tend to support setf rather than setaf.)
    	color_prompt=yes
        else
    	color_prompt=
        fi
    fi
    
    if [ "$color_prompt" = yes ]; then
        PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
    else
        PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
    fi
    unset color_prompt force_color_prompt
    
    # If this is an xterm set the title to user@host:dir
    case "$TERM" in
    xterm*|rxvt*)
        PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
        ;;
    *)
        ;;
    esac
    
    # enable color support of ls and also add handy aliases
    if [ -x /usr/bin/dircolors ]; then
        test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
        alias ls='ls --color=auto'
        #alias dir='dir --color=auto'
        #alias vdir='vdir --color=auto'
    
        alias grep='grep --color=auto'
        alias fgrep='fgrep --color=auto'
        alias egrep='egrep --color=auto'
    fi
    
    # colored GCC warnings and errors
    #export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'
    
    # some more ls aliases
    alias ll='ls -alF'
    alias la='ls -A'
    alias l='ls -CF'
    
    # Add an "alert" alias for long running commands.  Use like so:
    #   sleep 10; alert
    alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
    
    # Alias definitions.
    # You may want to put all your additions into a separate file like
    # ~/.bash_aliases, instead of adding them here directly.
    # See /usr/share/doc/bash-doc/examples in the bash-doc package.
    
    if [ -f ~/.bash_aliases ]; then
        . ~/.bash_aliases
    fi
    
    # enable programmable completion features (you don't need to enable
    # this, if it's already enabled in /etc/bash.bashrc and /etc/profile
    # sources /etc/bash.bashrc).
    if ! shopt -oq posix; then
      if [ -f /usr/share/bash-completion/bash_completion ]; then
        . /usr/share/bash-completion/bash_completion
      elif [ -f /etc/bash_completion ]; then
        . /etc/bash_completion
      fi
    fi
    

    使用source命令执行文件(source 命令用于在当前 Shell 环境中执行指定的脚本文件,并将其中的命令应用于当前 Shell)

    source ~/.bashrc
    
  3. 其它文件(不用于环境变量设置)

    • ~/.bash_logout

      每次退出Shell的时候执行该文件

    • ~/.bash_history

      保存用户命令的历史纪录

3、环境变量的优先级

​ 原则:同名的环境变量,如果在多个脚本中有配置,以最后执行的配置为准。

# 环境变量脚本文件的执行顺序
/etc/profile --> /etc/profile.d文件夹目录 --> /etc/bash.bashrc --> 用户的~/.bash_profile --> 用户的~/.bashrc

注:具体环境变量的执行顺序需要查看环境变量配置在脚本里的位置,比如:在/etc/profile文件中

# 在/etc/profile文件中

# /etc/profile: system-wide .profile file for the Bourne shell (sh(1))
# and Bourne compatible shells (bash(1), ksh(1), ash(1), ...).

# 此处为调用执行/etc/profile.d文件之前

if [ -d /etc/profile.d ]; then
  for i in /etc/profile.d/*.sh; do
    if [ -r $i ]; then
      . $i
    fi
  done
  unset i
fi
# 此处为调用执行/etc/profile.d文件之后

4、常用的环境变量

# PATH 可执行程序的搜索路径(重要掌握)
# PATH 存放的是目录列表,目录之间使用冒号:分隔
ubuntu@ubuntu:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/snap/bin

# 用户的工作目录主路径
ubuntu@ubuntu:~$ echo $HOME
/home/ubuntu

# 当前登录的用户名
ubuntu@ubuntu:~$ echo $LOGNAME
ubuntu

# 主机名
ubuntu@ubuntu:~$ echo $HOSTNAME
ubuntu

# 当前的Shell
ubuntu@ubuntu:~$ echo $SHELL
/bin/bash

# Linux系统的语言与字符集
ubuntu@ubuntu:~$ echo $LANG
en_US.UTF-8

# 生成一个随机数字
ubuntu@ubuntu:~$ echo $RANDOM
12219
  • 15
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
环境变量Linux中是指用来指定操作系统运行环境的一些参数。Linux是一个多用户的操作系统,每个用户都可以根据自己的需求来定制环境变量。Windows系统下,环境变量是通过设置系统属性中的环境变量来进行配置,而在Linux系统下,环境变量的配置是通过在用户的shell配置文件中进行设置。 在Linux系统中,环境变量的配置可以通过多种方法来实现。一种常用的方法是通过修改环境变量配置文件进行设置,比如在RedHat 9.0系统中,可以通过修改/etc/profile文件来添加或修改环境变量。另外一种常用的方法是通过代码来获取环境变量,可以使用C语言的getenv函数来获取指定环境变量的值。 方法一:通过代码获取环境变量(不常用): ```c int main(int argc, char *argv[], char *env[]) { for(int i = 0; env[i]; i++) { printf("%s\n", env[i]); } return 0; } ``` 或者 ```c int main() { extern char** environ; for(int i = 0; environ[i]; i++) { printf("%d->%s\n", i, environ[i]); } return 0; } ``` 方法二:通过代码获取环境变量(常用): ```c #include<stdio.h> #include<unistd.h> #include<stdlib.h> int main() { printf("%s\n",getenv("PATH")); printf("%s\n",getenv("HOME")); printf("%s\n",getenv("SHELL")); return 0; } ``` 以上是关于环境变量Linux系统中的一些基本介绍和配置方法。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值