在for循环中使用sudo

编程入门 行业动态 更新时间:2024-10-27 20:32:59
本文介绍了在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

本文发布于:2023-10-26 01:24:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1528673.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:sudo

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!