我想使用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
发布评论