su命令是用来切换用户身份的,默认情况下敲su并回车将切换到root身份,当然需要输入密码才能切换。
su [用户名]将会切换到指定用户,例如将用户从leconte切换到linuxer
[leconte@localhost ~]$ id uid=500(leconte) gid=500(leconte) groups=500(leconte) [leconte@localhost ~]$ [leconte@localhost ~]$ su linuxer 口令: bash-3.2$ id uid=501(linuxer) gid=501(linuxer) groups=501(linuxer) bash-3.2$这个用法想必大家平时都用过,也很清楚。
但是需要注意的是su的另外一个参数“-”,当指定该参数的时候,将会进入一个“login shell” ,即和该用户登录的情况完全一样。而不带参数“-”的时候进入的是一个“non-login shell”。那么问题就归结到“login shell”和“non-login shell“的区别上来了。
它们的差别在于,对于一个登录shell,bash在进入的时候会执行/etc/profile,~/.bash_profile,~/.bash_login, and ~/.profile中的内容,退出的时候会执行~/.bash_logout中的内容。而对于一个非登录shell,bash进入的时候会执行/etc/bash.bashrc,~/.bashrc中的内容。
通过一个例子来看一下,假如用户linuxer的 .bash_profile和.bashrc内容分别如下:
bash-3.2$ cat .bash_profile
.bash_profile
export TEST=login-shell bash-3.2$ cat .bashrc
.bashrc
export TEST2=non-login-shell很简单,我们在文件里分别设置了两个环境变量,然后用su linuxer和su -linuxer分别进入后查看环境变量,结果如下
[leconte@localhost ~]$ su linuxer 口令: bash-3.2$ env | grep TEST TEST2=non-login-shell[leconte@localhost ~]$ su - linuxer 口令: -bash-3.2$ env | grep TEST TEST=login-shell可以看到,su linuxer进入非登录shell,.bashrc被执行;su – linuxer进入登录shell,.bash_profile被执行。