简体   繁体   English

代码不适用于sh -c,但直接在sh上工作

[英]Code does not work with sh -c, but works on sh directly

$ sh
sh-3.2$ if
> ps -ef | grep apple ;
> then
> echo APPLE 
> fi ;
lazer   7584  7571  0 04:36 pts/4    00:00:00 grep apple
APPLE
sh-3.2$ exit
exit
$ which sh
/bin/sh
$ /bin/sh -c if ps -ef | grep apple ; then echo APPLE fi ;
bash: syntax error near unexpected token `then'
$

As above, my simple if statement works as expected when executed line by line but gives me the following error when executed using sh -c : 如上所述,我的简单if语句在逐行执行时按预期工作,但在使用sh -c执行时给出了以下错误:

bash: syntax error near unexpected token `then' bash:意外令牌附近的语法错误`then'

What am I missing here? 我在这里错过了什么?

Your interactive shell will be escaping the invocation via sh -c . 您的交互式shell将通过sh -c转义调用。 In particular it's taking everyting after the semi-colon as a new statement. 特别是它将分号后的每一个作为一个新的陈述。

Quote everything that you're feeding to /bin/sh eg 引用你要提供给/bin/sh所有东西,例如

$ /bin/sh -c "if ps -ef | grep apple ; then echo APPLE fi ;"

I think you may also need to delimit further using semi-colons given that you're condensing everything onto one line, and would perhaps suggest you could use a heredoc . 我认为您可能还需要使用分号进一步划分,因为您将所有内容压缩到一条线上,并且可能建议您使用heredoc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么sh shebang不起作用? - Why does this sh shebang not work? 函数不适用于sh(但适用于bash) - function doesn't work with sh (but works for bash) 简单的 Git Bash.sh windows 上的脚本更改目录不起作用。 .sh 脚本中的基本更改目录 - Simple Git Bash .sh Script on windows to change directory does not work. Basic change directory in .sh script Git Bash.sh windows 上的脚本更改目录不起作用。 .sh 脚本中的基本更改目录 - Git Bash .sh Script on windows to change directory does not work. Basic change directory in .sh script 帮助这个.sh代码 - Help with this .sh code `如何找到<path> -name &quot;*.sh&quot; -exec chmod +x \\{\\} \\;` 工作吗? - How does `find <path> -name "*.sh" -exec chmod +x \{\} \;` work? 为什么此sed命令在终端中起作用,但在bash“ .sh”脚本中却不起作用 - Why Does this sed command work in terminal but not in bash “.sh” script 为什么 SIGHUP 在 Alpine Docker 容器中的 busybox sh 上不起作用? - Why does SIGHUP not work on busybox sh in an Alpine Docker container? 为什么“echo -n”命令在 .sh 脚本中不起作用? - why does "echo -n" command not work in a .sh script? 从终端直接执行 docker 可以正常工作,但从 .sh 脚本内部执行时则不行? - Executing docker from terminal directly works fine but not when executed from inside a .sh script?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM