如何使用 su 以该用户身份执行 bash 脚本的其余部分? [英] How do I use su to execute the rest of the bash script as that user?
问题描述
我编写了一个脚本,它将一个字符串作为参数,该字符串是用户名和项目的串联.该脚本应该根据项目字符串将 (su) 切换到用户名,将 cd 切换到特定目录.
I've written a script that takes, as an argument, a string that is a concatenation of a username and a project. The script is supposed to switch (su) to the username, cd to a specific directory based upon the project string.
我基本上想做:
su $USERNAME;
cd /home/$USERNAME/$PROJECT;
svn update;
问题是一旦我做了一个 su... 它就在那里等着.这是有道理的,因为执行流程已经传递到切换到用户.一旦我退出,其余的事情就会执行,但不能按预期工作.
The problem is that once I do an su... it just waits there. Which makes sense since the flow of execution has passed to switching to the user. Once I exit, then the rest of the things execute but it doesn't work as desired.
我在 svn 命令前添加了 su 但命令失败(即它没有更新所需目录中的 svn).
I prepended su to the svn command but the command failed (i.e. it didn't update svn in the directory desired).
如何编写允许用户切换用户和调用 svn(除其他外)的脚本?
How do I write a script that allows the user to switch user and invoke svn (among other things)?
推荐答案
诀窍是使用sudo"命令而不是su"
The trick is to use "sudo" command instead of "su"
你可能需要添加这个
username1 ALL=(username2) NOPASSWD: /path/to/svn
到您的/etc/sudoers 文件
to your /etc/sudoers file
并将您的脚本更改为:
sudo -u username2 -H sh -c "cd /home/$USERNAME/$PROJECT; svn update"
其中 username2 是您要运行 SVN 命令的用户,username1 是运行脚本的用户.
Where username2 is the user you want to run the SVN command as and username1 is the user running the script.
如果您需要多个用户来运行此脚本,请使用 %groupname
而不是 username1
If you need multiple users to run this script, use a %groupname
instead of the username1
这篇关于如何使用 su 以该用户身份执行 bash 脚本的其余部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!