在 CentOS 中 alias 看起来“无效”,通常不是 alias 本身的问题,而是生效范围 / 加载时机 / 使用场景不对。下面按最常见原因给你系统排查。
| 现象 | 原因 |
|---|---|
| alias 只在当前终端有效 | 只在当前 shell 设置,未写入配置文件 |
| 重新登录后失效 | 没写入 ~/.bashrc 或 ~/.bash_profile |
| sudo 后 alias 无效 | sudo 启动的是新 shell |
| 脚本中 alias 无效 | 脚本默认不展开 alias |
| 用 zsh / dash 但改了 bash 配置 | shell 不一致 |
| alias 被后面的配置覆盖 | 加载顺序问题 |
vim ~/.bashrc
添加:
alias ll='ls -lh'
alias cls='clear'
然后执行:
source ~/.bashrc
✅ 重新登录 / 新开终端即可生效
alias ll='ls -lh'
只在当前 shell 生效
写入配置文件:
~/.bashrc # 交互式 shell(最常用)
~/.bash_profile # 登录 shell
alias docker='sudo docker'
sudo docker ps
❌ 不会生效
sudo 会启动 新的 shell 环境,不会继承当前 alias
sudo docker ps
alias sdocker='sudo docker'
#!/bin/bash
alias ll='ls -lh'
ll
❌ 默认不生效
脚本中 alias 不展开
#!/bin/bash
shopt -s expand_aliases
alias ll='ls -lh'
ll
⚠️ 不推荐在脚本中大量使用 alias
查看当前 shell:
echo $SHELL
| Shell | 配置文件 |
|---|---|
| bash | ~/.bashrc |
| zsh | ~/.zshrc |
| dash | 不支持 alias 交互 |
✅ 如果你用的是 zsh,改 ~/.bashrc 是没用的
alias ll
type ll
grep -R "alias" ~/.bashrc ~/.bash_profile /etc/bashrc
vim /etc/bashrc
⚠️ 会影响所有用户,升级可能被覆盖
echo $SHELL
cat ~/.bashrc | grep alias
source ~/.bashrc
alias
你可以直接贴:
我可以一步一步帮你查 ✅