PATH 环境变量详解 — 在 Linux 上添加工具目录
PATH 是什么、shell 为何按顺序搜索它,以及把个人脚本目录安全加入 PATH 的正确做法。
执行 export PATH="$HOME/.local/bin:$PATH"(并写入 ~/.bashrc 以便永久生效),之后即可在任意位置直接运行自己 bin 目录里的脚本。
01命令
命令
$ echo $PATH && export PATH="$HOME/.local/bin:$PATH"02作用说明
PATH 是一个冒号分隔的目录列表,你每输入一个命令名,shell 都会按从左到右的顺序在其中搜索,第一个匹配的生效——'command not found' 只说明列表里没有任何目录包含这个名字。把目录放在最前面($HOME/.local/bin:$PATH)会让你的脚本优先于系统工具,追加在末尾(:...$PATH)则优先级最低——当需要遮盖 python 之类的命令时,这个区别至关重要。把 export 写入 ~/.bashrc(或 ~/.zshrc)让每个新终端都继承,再用 echo $PATH 和 command -v 你的脚本 验证结果。
03风险
!注意: 绝对不要把 '.' 或空条目放进 PATH:shell 会在你当前所在的任意目录里运行程序,这正是攻击者在共享目录里放置假冒 'ls' 程序的常用手段。
04撤销
撤销
$ Remove the export PATH line from ~/.bashrc / ~/.zshrc and reopen the terminal05来源
- which(1) — Linux manual page依据: which resolves command names against PATH, demonstrating the directory search order the shell uses.
- bash(1) — Linux manual page依据: Documents PATH: a colon-separated list of directories searched in order for command execution; empty entries mean the current directory.
最后验证: 2026-09-18 · 分类: 开发者