1. 先执行sudo,保证之后执行sudo时不必再输入密码(此步骤可忽略)
[gaoqihua@iZt4nip56cf5a8v01ya8z7Z ~]$ sudo ls
[sudo] password for gaoqihua:
arthas-boot.jar
2. sudo java确实提示找不到命令
[gaoqihua@iZt4nip56cf5a8v01ya8z7Z ~]$ sudo java -version
[sudo] password for gaoqihua:
sudo: java: command not found
[gaoqihua@iZt4nip56cf5a8v01ya8z7Z ~]$
[gaoqihua@iZt4nip56cf5a8v01ya8z7Z ~]$
3. 验证环境变量的存在
4. 开始解决:在个人用户目录下编辑.bashrc, 添加以下内容:alias sudo="sudo env PATH=$PATH" 并退出
[gaoqihua@iZt4nip56cf5a8v01ya8z7Z ~]$ vi ~/.bashrc
.bashrc
Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
以下命令表示:自定义sudo命令,当执行sudo时不在时系统的sudo命令,而是会加载系统环境变量。关于alias命令,参考:https://www.runoob.com/linux/linux-comm-alias.html
alias sudo="sudo env PATH=$PATH"
Uncomment the following line if you don't like systemctl's auto-paging feature:
export SYSTEMD_PAGER=
User specific aliases and functions
~
".bashrc" 11L, 263C written
5. 添加后,执行sudo java仍然提示找不到。这是因为修改没有生效
[gaoqihua@iZt4nip56cf5a8v01ya8z7Z ~]$ sudo java -version
sudo: java: command not found
6. 让修改生效起来
[gaoqihua@iZt4nip56cf5a8v01ya8z7Z ~]$ source ~/.bashrc
7. 再次执行sudo java,会发现已经显示正确的java版本信息
[gaoqihua@iZt4nip56cf5a8v01ya8z7Z ~]
[gaoqihua@iZt4nip56cf5a8v01ya8z7Z ~]
[gaoqihua@iZt4nip56cf5a8v01ya8z7Z ~] cat ~/.bashrc
.bashrc
Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
以下命令表示:自定义sudo命令,当执行sudo时不在时系统的sudo命令,而是会加载系统环境变量。关于alias命令,参考:https://www.runoob.com/linux/linux-comm-alias.html
alias sudo="sudo env PATH=$PATH"
Uncomment the following line if you don't like systemctl's auto-paging feature:
export SYSTEMD_PAGER=
User specific aliases and functions
[gaoqihua@iZt4nip56cf5a8v01ya8z7Z ~]$