In my shell script i have the following line:
export PATH=$PATH:/home/$USER/somedir
Say im logged in as user mike. I need to execute the shell script as root, so i run it as sudo filename.sh, so $USER becomes root in my path in that case.
I want it to be that of the user running the script, ie mike instead of root. Is there a way to achieve this?
Thank You
Do you have to use /home/$USER
, or will $HOME
do the trick? IIRC, sudo
doesn't override the value of $HOME
.
Use $SUDO_USER
(if you insist on using $USER
directly, set its value as shown):
$ cat script.sh
#!/bin/bash
if [ "$SUDO_USER" != "" ]; then
USER=$SUDO_USER;
fi
export PATH=$PATH:/home/$USER/somedir
Or cheat using $USER
as the first parameter to the script (error checking is an exercise for the reader):
$ cat script.sh
#!/bin/bash
USER=$1
export PATH=$PATH:/home/$USER/somedir
Then:
$ sudo ./script.sh $USER
Or use $HOME
, as suggested by Chris Jester-Young. You could use bash to remove the "/home/" prefix, but that would be an ugly hack.
If you're willing to use su
instead of sudo
, you can do
su -cp filename.sh
to execute the command while preserving your environment.
您可以尝试使用$ UID,该$ UID仍应设置为用户的真实ID号,并以此为基础从密码数据库中检索其名称。
If you need to preserve environnement, you can use the -E option of sudo. But it needs some configuration and security politics ... That applies if the $HOME solution proposed by Chris JY does not apply as it is simpler.
my 2 cents
sudo is different form "root" user. If any user has sudo privileges, that means he has the admin rights that are available with the user "root". That is, using sudo doesn't change the user to root.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.