Search code examples
m4

How to properly detect whether a define/variable in m4 is empty while it can include commas?


How can I detect in m4 template whether define/variable is empty while it also can contain commas? It's passed through m4 arguments, so it can contain any value.

Problem is that when I write the ifelse condition without putting the variable inside quotes, it works, but when the var contains commas, it breaks the template. If I put it inside quotes, empty string won't get detected.

Example #1:

File template.m4:

ifelse(`_VAR_', `', `empty; "_VAR_"', `non-empty; "_VAR_"')

Results:

$ m4 -D _VAR_=text template.m4
non-empty; "text"
$ m4 -D _VAR_="a, a, INJECTED" template.m4
non-empty; "a, a, INJECTED"

These are ok.

$ m4 -D _VAR_= template.m4
non-empty; ""
$ m4 -D _VAR_="" template.m4
non-empty; ""

Problem, expected: empty; "" (in both cases).

Example #2:

File template.m4:

ifelse(_VAR_, `', `empty; "_VAR_"', `non-empty; "_VAR_"')

Results:

$ m4 -D _VAR_=test template.m4
non-empty; "test"
$ m4 -D _VAR_= template.m4
empty; ""
$ m4 -D _VAR_="" template.m4
empty; ""

These are ok.

$ m4 -D _VAR_="a, a, INJECTED" template.m4
INJECTED

Wasn't handled correctly, expected: non-empty; "a, a, INJECTED"

My environment

  • OS: Xubuntu 18.04 LTS 64bit
  • m4: 1.4.18

Solution

  • I think the following will be your desire:

    ifelse(defn(`_VAR_'),`',`empty',`non empty: _VAR_')