从命令提示符处执行if语句


19

在bash中,我可以执行以下操作:

if [ -f /tmp/test.txt ]; then echo "true"; fi

但是,如果我sudo在前面添加,它将不再起作用:

sudo if [ -f /tmp/test.txt ]; then echo "true"; fi
-bash: syntax error near unexpected token `then'

我该如何运作?



更好的做法是sudotest和和/或仅echo。不是整个if陈述。
jippie 2012年

你的意思是if sudo test?是的,那会更好。如果test没有if,我将无法使用,因为否则会设置退出代码。
m33lky 2012年

Answers:


14

sudo使用exec而不是通过外壳解释器执行其参数。因此,它仅限于实际的二进制程序,并且不能使用外壳函数,别名或内置程序(if是内置程序)。请注意,-i-s选项可分别用于在登录或非登录外壳程序中(或仅外壳程序)以交互方式执行给定命令;请注意,您必须转义分号或引用命令)。

$ sudo if [ -n x ]; then echo y; fi
-bash: syntax error near unexpected token `then'
$ sudo if [ -n x ]\; then echo y\; fi
sudo: if: command not found
$ sudo -i if [ -n x ]\; then echo y\; fi
y
$ sudo -s 'if [ -n x ]; then echo y; fi'
y

那么,如果我使用-i-s,则if语句将被正确评估?
m33lky 2012年

1
是的,只要正确引用或转义它即可。看到我的编辑。
2012年

9

尝试通过外壳将行作为字符串参数调用。

sudo /bin/sh -c 'if [ -f /tmp/test.txt ]; then echo "true"; fi'
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.