linux - makefile if/else 中的 Shell 循环语法

标签 linux shell makefile gnu-make gnu

我已经循环了,我需要添加到它的 if else 语句中, 如果值 ==app1 打印 x 否则打印 y

我尝试过以下方法 但是当我添加 else 时,我遇到了语法错误,

我做错了什么?

runners:
    @for a in $(apps) ; do
       if (( a ==  "app1"));then
        echo first: $$v ;
       else
        echo second: $$v ;
        fi
     done

最佳答案

  1. 我更喜欢使用 bash 作为我的 shell,因为我已经习惯了。因此我使用SHELL:=/bin/bash在我的 makefile 的顶部。但是当系统不提供/bin/bash 时,整个 makefile 就会失败..

  2. 如果您想对配方中的所有行使用相同的 shell,可以使用特殊目标 .ONESHELL这可以防止您在每行后面使用 ;\ 且后面没有空格(容易出错)。但如果您使用 .ONESHELL ,那么对于 makefile 中的所有配方都是如此(我使用它,但您可能不想要)。

  3. 如果 runners 不是一个文件(看起来是这样,因为您没有在配方中创建文件),我建议将其设为 .PHONY 。当碰巧有一个名为 runners 的文件而始终执行虚假目标时,您的版本可能会阻止 make 执行它。

  4. 双括号((...))用于算术扩展。它根本无法比较字符串。使用单括号或双括号。请参阅this great post .

  5. 我还认为您想要打印 a,因此将 $$v 替换为 $$a

所以总的来说,只要你有/bin/bash 就可以完美地工作:

SHELL:=/bin/bash
.ONESHELL:
.PHONY: runners
apps:=app2 app3 app1 app5
runners:
    @for a in $(apps) ; do  <<-- ; between commands as usual
      if [[ "$$a" ==  "app1" ]]; then
        echo first: $$a  <<-- no need for ; because of .ONESHELL
      else
        echo second: $$a
      fi
    done

Output:

second: app2
second: app3
first: app1
second: app5

关于linux - makefile if/else 中的 Shell 循环语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52310971/

相关文章:

linux - 根据从高到低对 Linux 文件中的字段进行排序

Linux命令不起作用

bash - shell 脚本: Portable way to programmably obtain the CPU vendor on POSIX systems

bash - ffmpeg 命令在 python 中使用时出错

c++ - 如果什么都不做,请检查 Makefile

C++ Make 显示 include 正在哪里搜索文件

mysql - 如何在 MySQL 中获取用户输入?

linux - .bash_profile 中的路径设置不会反射(reflect)在整个系统中

shell - 管道是否保证在任何 POSIX shell 中创建子 shell?

c++ - 更改 Eclipse CDT 项目的输出目录