在 CentOS 中 alias 失效 是个很常见的问题,通常不是 alias 本身坏了,而是在错误的 shell / 配置文件 / 会话中生效。下面按常见原因一步步排查。
echo $SHELL
ps -p $$
常见情况:
~/.bashrc~/.zshrc✅ 推荐用 bash
vim ~/.bashrc
例如:
alias ll='ls -lh'
alias cls='clear'
保存后执行:
source ~/.bashrc
⚠️ 注意
.bash_profile 只在登录 shell生效.bashrc 才在交互式 shell生效(推荐)CentOS 默认:
ssh user@host → 启动的是 login shell.bash_profile,不自动加载 .bashrc编辑 ~/.bash_profile,加入:
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
保存后重新登录。
#!/bin/bash
alias ll='ls -lh'
ll # ❌ 不生效
✅ 解决办法:
shopt -s expand_aliases
alias ll='ls -lh'
或 直接用函数 / 完整命令
alias
如果没看到你的 alias,说明没加载成功。
sudo ll
❌ alias 不会继承给 sudo
✅ 正确方式:
sudo ls -lh
或:
sudo bash -c 'alias ll="ls -lh"; ll'
alias 不会在 cron 或非交互 shell 中生效
✅ 解决:
✅ alias 写在 ~/.bashrc
✅ 执行过 source ~/.bashrc
✅ 当前 shell 是 bash
✅ 没有在 sudo / 脚本 / cron 中使用
✅ .bash_profile 加载了 .bashrc
bash
source ~/.bashrc
alias
如果能看到 alias,说明没问题。
如果你愿意,可以把以下信息发我,我可以精确分析:
cat /etc/centos-release)echo $SHELL)我可以直接帮你定位 ✅