在for循环中使用sudo [英] Using sudo with for loop

查看:65
本文介绍了在for循环中使用sudo的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我收到以下错误:

-bash: syntax error near unexpected token `do'

我可能忽略了一件非常简单的事情.有帮助吗?

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

推荐答案

sudo想要一个程序(+参数)作为参数,而不是一个Shell脚本.不过,您可以执行以下操作:

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'

请注意单引号.如果使用双引号,则您的外壳将尝试在sudo(或更确切地说,由其运行的外壳)看到它之前扩展 $ i .

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.注释中指出(仅六年后),还有一个单独的问题是,如果要遍历目录中的文件,则正确的语法是/dir/*中的 i. for 接受一个列表,而/dir 是一个包含一项的列表....由于通配符扩展,/dir/* 扩展为/dir 中的文件列表.

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.

这篇关于在for循环中使用sudo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆