Sudo users can not find problem-solving environment variables

For security reasons, the use sudo to execute the command will be executed in a minimal environment, environment variables are reset to the default state. So user-defined settings content of the PATH variable does not include
add the following .bashrc in the user's home directory sudo can be solved in

$ vim ~/.bashrc

alias sudo="sudo env PATH=$PATH"

There is such a shell script, which reads as follows, did not give its permission x

vim test.sh

#!/bin/bash

echo "${PATH}"
# 执行该脚本,可以看到echo输出的结果
[test_ops@iZ2zej3o3e9be3aoukimfzZ ~]$ 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}变量结果
[test_ops@iZ2zej3o3e9be3aoukimfzZ ~]$ sudo bash test.sh
/sbin:/bin:/usr/sbin:/usr/bin
# 因其没有x权限,所以无法这样执行
[test_ops@iZ2zej3o3e9be3aoukimfzZ ~]$ sudo ./test.sh
sudo: ./test.sh: command not found
# 给该脚本加上x权限
[test_ops@iZ2zej3o3e9be3aoukimfzZ ~]$ chmod a+x test.sh
[test_ops@iZ2zej3o3e9be3aoukimfzZ ~]$ ll
total 4
-rwxrwxr-x 1 test_ops test_ops 28 Sep 11 11:55 test.sh
# 可以执行,但结果相同
[test_ops@iZ2zej3o3e9be3aoukimfzZ ~]$ sudo ./test.sh
/sbin:/bin:/usr/sbin:/usr/bin
# 在用户的主目录里的.bashrc中添加如下内容
[test_ops@iZ2zej3o3e9be3aoukimfzZ ~]$ vim ~/.bashrc

alias sudo="sudo env PATH=$PATH"

# 退出登陆后再次执行,其结果正是自己想要的效果
[test_ops@iZ2zej3o3e9be3aoukimfzZ ~]$ 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
[test_ops@iZ2zej3o3e9be3aoukimfzZ ~]$ 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
[test_ops@iZ2zej3o3e9be3aoukimfzZ ~]$ 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
[test_ops@iZ2zej3o3e9be3aoukimfzZ ~]$ ./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
[test_ops@iZ2zej3o3e9be3aoukimfzZ ~]$

Reference connection: https: //blog.csdn.net/jiangxuege/article/details/82592258

Guess you like

Origin www.cnblogs.com/sanduzxcvbnm/p/11505546.html