在 CentOS 中 alias 不生效 是很常见的问题,通常不是 alias 写错了,而是加载时机或作用范围不对。下面按最常见原因逐一说明。
不同 shell、不同登录方式,读取的文件不同:
| Shell | 交互式登录 | 交互式非登录 | 非交互 |
|---|---|---|---|
| bash | ~/.bash_profile |
~/.bashrc |
不读 alias |
| bash | /etc/profile |
/etc/bashrc |
不读 alias |
✅ 推荐位置
~/.bashrc
❌ 常见错误
写在 ~/.bash_profile 但用的是终端直接开 bash
source ~/.bashrc
或
. ~/.bashrc
⚠️ 新开终端也会重新加载
sh test.sh
# 里面 alias 无效
alias 只在交互式 shell 生效
shopt -s expand_aliases
source ~/.bashrc
✅ 更推荐:用函数代替 alias
mygrep() {
grep --color=auto "$@"
}
echo $SHELL
ps -p $$
如果是:
zsh → 改 ~/.zshrcsh → alias 基本不可用例如:
alias ll='ls -l'
alias ll='ls'
后写的会覆盖前面的
检查:
alias
如果没有你定义的,说明没加载
sudo ll
❌ 不会生效
✅ 解决:
sudo alias ll='ls -l' # 没用
正确方式:
sudo ls -l
echo $SHELL
~/.bashrc
source ~/.bashrc
alias
如果你愿意,可以把:
发出来,我可以直接帮你定位是哪一种情况。