出于安全方面的考虑,使用sudo执行命令将在一个最小化的环境中执行,环境变量都重置成默认状态。所以PATH这个变量不包括用户自定义设置的内容
在sudo用户的主目录里的.bashrc中添加如下内容即可解决
$ vim ~/.bashrc
alias sudo="sudo env PATH=$PATH"
有这样一个shell脚本,其内容如下,没有给其x权限
vim test.sh
#!/bin/bash
echo "${PATH}"
# 执行该脚本,可以看到echo输出的结果
[[email protected] ~]$ bash test.sh
/opt/ossutil:/opt/openresty/nginx/sbin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/opt/jdk1.8/bin:/opt/jdk1.8/jre/bin:/home/test_ops/.local/bin:/home/test_ops/bin
# 但是加上sudo,上述结果就不显示了,而是一个系统默认的${PATH}变量结果
[[email protected] ~]$ sudo bash test.sh
/sbin:/bin:/usr/sbin:/usr/bin
# 因其没有x权限,所以无法这样执行
[[email protected] ~]$ sudo ./test.sh
sudo: ./test.sh: command not found
# 给该脚本加上x权限
[[email protected] ~]$ chmod a+x test.sh
[[email protected] ~]$ ll
total 4
-rwxrwxr-x 1 test_ops test_ops 28 Sep 11 11:55 test.sh
# 可以执行,但结果相同
[[email protected] ~]$ sudo ./test.sh
/sbin:/bin:/usr/sbin:/usr/bin
# 在用户的主目录里的.bashrc中添加如下内容
[[email protected] ~]$ vim ~/.bashrc
alias sudo="sudo env PATH=$PATH"
# 退出登陆后再次执行,其结果正是自己想要的效果
[[email protected] ~]$ sudo ./test.sh
/opt/ossutil:/opt/openresty/nginx/sbin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/opt/jdk1.8/bin:/opt/jdk1.8/jre/bin
[[email protected] ~]$ sudo bash test.sh
/opt/ossutil:/opt/openresty/nginx/sbin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/opt/jdk1.8/bin:/opt/jdk1.8/jre/bin
[[email protected] ~]$ bash test.sh
/opt/ossutil:/opt/openresty/nginx/sbin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/opt/jdk1.8/bin:/opt/jdk1.8/jre/bin:/home/test_ops/.local/bin:/home/test_ops/bin
[[email protected] ~]$ ./test.sh
/opt/ossutil:/opt/openresty/nginx/sbin:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/opt/jdk1.8/bin:/opt/jdk1.8/jre/bin:/home/test_ops/.local/bin:/home/test_ops/bin
[[email protected] ~]$
参考连接:https://blog.csdn.net/jiangxuege/article/details/82592258
原文地址:https://www.cnblogs.com/sanduzxcvbnm/p/11505546.html
时间: 2024-10-22 23:21:59