BASH:if 语句执行命令和函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6606731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:19:12  来源:igfitidea点击:

BASH: if statement execute command and function

bashif-statementbash-function

提问by drewrockshard

I've run into an issue in which I think should be easy to resolve, but for the life of me, I can't figure it out. Could be that it's really late; not sure.

我遇到了一个我认为应该很容易解决的问题,但对于我的生活,我无法弄清楚。可能是真的晚了;没有把握。

So I have a shell script and I have an if statement that I need to run. The problem is that I have a function inside this bash script that I am using to actually build part of this find command inside the if statement. I want to know how I can do both, without receiving an error [: too many arguments.

所以我有一个 shell 脚本,我有一个需要运行的 if 语句。问题是我在这个 bash 脚本中有一个函数,我用来在 if 语句中实际构建这个 find 命令的一部分。我想知道如何在不收到错误的情况下做到这两点[: too many arguments

Here's the current code:

这是当前的代码:

if [ -n `find ./ `build_ext_names`` ];then

That's all I really need to post. I need to figure out how to run that build_ext_namesinside that find command, which in-turn is inside the ifstatement

这就是我真正需要发布的内容。我需要弄清楚如何build_ext_names在该 find 命令中运行该命令,而该命令又位于 if 语句中

回答by l0b0

Michael Aaron Safyanhas the right idea, but to fix the immediate problem you can just use the simpler $(command)construct instead of ```command` `` for command substitution. It allows for much simpler nesting:

Michael Aaron Safyan的想法是正确的,但要解决眼前的问题,您可以使用更简单的$(command)构造而不是 ```command``` 进行命令替换。它允许更简单的嵌套:

if [ -n "$(find ./ "$(build_ext_names)")" ]; then

回答by Michael Aaron Safyan

This is easier if you split it up:

如果你把它分开,这会更容易:

function whateverItIsYouAreTryingToDo() {
   local ext_names=$(build_ext_names)
   local find_result=$(find ./ $ext_names)
   if [ -n "$find_result" ]  ; then
       # Contents of if...
   fi
}