背景
前几天用Linux的时候遇到一个问题,使用su
切换用户时,用户已经切换了,但是环境变量却还是原来用户的,导致命令执行不了。
现象
首先,用普通用户登录Linux,运行echo $PATH
:
square@debian:~$ whoami
square
square@debian:~$ echo $PATH
/home/square/.local/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
随后,使用su root
切换到root用户:
square@debian:~$ su root
root@debian:~# whoami
root
root@debian:~# echo $PATH
/home/square/.local/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
root@debian:~# source /etc/profile
root@debian:~# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
可以看到,切换到root用户后,环境变量是之前的普通用户的,必须手动执行source /etc/profile
,环境变量才变成root用户的。
问题原因
su
只获取用户的权限,没有获取环境变量;
su -
获取用户的权限和环境变量;
# sudo asks for *your* password and must be configured via /etc/sudoers
sudo -s # Shell for superuser
sudo -i # Login shell for superuser
sudo -u jimmy -s # Shell for user "jimmy"
sudo -u jimmy -i # Login shell for user "jimmy"
# su asks for the root password and usually requires no configuration
su # Shell for superuser
su - # Login shell for superuser
su jimmy # Shell for "jimmy"
su - jimmy # Login shell for "jimmy"
解决方案
使用su -
切换root用户,
square@debian:~$ echo $PATH
/home/square/.local/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games
square@debian:~$ su - root
Password:
root@debian:~# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
标签:bin,local,su,debian,切换,Linux,root,环境变量,usr
From: https://www.cnblogs.com/wn98/p/17538928.html