Path

PATH 是一个环境变量,它指引 Linux 系统在指定目录搜索可执行的文件。PATH 变量使用户能够在不指定路径的情况下运行命令。当用户在终端中调用命令时,系统会执行程序。因此,Linux 必须能够找到正确的可执行文件。PATH 指定程序目录并指引系统在何处搜索要运行的程序。

查看PATH目录

echo $PATH

如何在 Linux 中将目录添加到 PATH?

默认情况下,Linux会添加特定的PATH,用户想添加自定义目录方法有两种:

  • 添加临时的 PATH:临时将目录添加到 PATH 仅影响当前终端会话。用户关闭终端后,目录将被删除。
  • 添加永久的 PATH:会话,重启都不会删除该目录,永久存在.

示例:

/home/demo文件夹为例,演示两种添加PATH的用法.

添加临时的 PATH

export PATH="/home/demo:$PATH"
查看PATH目录变化:

添加之前:

root@S:~# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

添加之后:

root@S:~# echo $PATH
/home/demo:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

添加永久的 PATH

方法:将 export PATH="/home/demo:$PATH" 添加到.bashrc中末尾

查看PATH变化

添加之前

root@S:~# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

添加之后

root@S:~# echo $PATH
/home/demo:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

查看.bashrc变化

添加之前

# ~/.bashrc: executed by bash(1) for non-login shells.

# Note: PS1 and umask are already set in /etc/profile. You should not
# need this unless you want different defaults for root.
# PS1='${debian_chroot:+($debian_chroot)}\h:\w\$ '
# umask 022

# You may uncomment the following lines if you want `ls' to be colorized:
# export LS_OPTIONS='--color=auto'
# eval "$(dircolors)"
# alias ls='ls $LS_OPTIONS'
# alias ll='ls $LS_OPTIONS -l'
# alias l='ls $LS_OPTIONS -lA'
#
# Some more alias to avoid making mistakes:
# alias rm='rm -i'
# alias cp='cp -i'
# alias mv='mv -i'

添加之后

root@S:~# cat .bashrc 
# ~/.bashrc: executed by bash(1) for non-login shells.

# Note: PS1 and umask are already set in /etc/profile. You should not
# need this unless you want different defaults for root.
# PS1='${debian_chroot:+($debian_chroot)}\h:\w\$ '
# umask 022

# You may uncomment the following lines if you want `ls' to be colorized:
# export LS_OPTIONS='--color=auto'
# eval "$(dircolors)"
# alias ls='ls $LS_OPTIONS'
# alias ll='ls $LS_OPTIONS -l'
# alias l='ls $LS_OPTIONS -lA'
#
# Some more alias to avoid making mistakes:
# alias rm='rm -i'
# alias cp='cp -i'
# alias mv='mv -i'

export PATH="/home/demo:$PATH"