Using sudo with for loop

左心房为你撑大大i 提交于 2020-12-29 05:17:27

问题


I want to run a simple for loop command with sudo, but it isn't working:

sudo -i -u user for i in /dir; do echo $i; done

I get the following error:

-bash: syntax error near unexpected token `do'

Probably a very simple thing I am overlooking. Any help?


回答1:


sudo wants a program (+arguments) as a parameter, not a piece of shell script. You can do this, though:

sudo -i -u user sh -c 'for i in /dir; do echo $i; done'

Note the single quotes. If you used double quotes, your shell would try to expand the $i before sudo (or, rather, the shell run by it) ever sees it.

PS. a separate problem, as pointed out in a comment (only six years later), is that if you want to iterate over the files in a directory, the proper syntax is for i in /dir/*. for accepts a list, and /dir is a list... with one item. /dir/* expands to a list of files in /dir due to wildcard expansion.




回答2:


You can try sudo bash -c 'commands here'




回答3:


Put the sudo inside the loop:

for i in /dir; do
    sudo -u user somecommand $i
done

This won't work without extra steps if you need the other user's permissions to generate the glob for the loop, for example.



来源:https://stackoverflow.com/questions/10889072/using-sudo-with-for-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!