bash 将 sudo 与 for 循环一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10889072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 02:26:42  来源:igfitidea点击:

Using sudo with for loop

bashfor-loopsudo

提问by Axl

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

我想用 sudo 运行一个简单的 for 循环命令,但它不起作用:

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?

可能是我忽略的一件非常简单的事情。有什么帮助吗?

回答by Jan Krüger

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

sudo 想要一个程序(+arguments)作为参数,而不是一段 shell 脚本。不过,您可以这样做:

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 $ibefore sudo (or, rather, the shell run by it) ever sees it.

注意单引号。如果您使用双引号,您的 shell 会尝试$i在 sudo(或者更确切地说,由它运行的 shell)看到它之前扩展它。

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/*. foraccepts a list, and /diris a list... with one item. /dir/*expands to a list of files in /dirdue to wildcard expansion.

附注。正如评论中指出的那样(仅六年后),另一个问题是,如果您想遍历目录中的文件,正确的语法是for i in /dir/*. for接受一个列表,并且/dir是一个列表......包含一个项目。由于通配符扩展,扩展/dir/*为文件列表/dir

回答by BLaZuRE

You can try sudo bash -c 'commands here'

你可以试试 sudo bash -c 'commands here'

回答by evil otto

Put the sudo inside the loop:

将 sudo 放入循环中:

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.

例如,如果您需要其他用户的权限来为循环生成 glob,那么如果没有额外的步骤,这将无法工作。