Distinguish between empty and non-existing environment variables in Octave

Viewed 230

I mean to tell in Octave if a given environment variable exists.

Something that works in most cases is size(getenv(varname))(1). If this equals to 1, the variable exists. But if this equals 0, the variable may not exist or it may exist and be set to a null value.

How can I distinguish these two cases? Can this be done "natively" in Octave?

I would like my script to work irrespective of the host OS and shell.

In POSIX one could issue a system call and read the results. Then for Windows one would have to check in another way, and write a wrapper that deals with both cases separately.


EDIT (tl;dr)

I was using a defined/not-defined environment variable to handle compilation cases, via a combination of

if(DEFINED ENV{ENV_TEST})
  add_definitions(-DENV_TEST=$ENV{ENV_TEST})
endif()

in CMakeLists.txt and

#ifdef ENV_TEST
    cout << "ENV_TEST is defined and set to \'" ENV_TEST "\'" << endl;
#else
    cout << "ENV_TEST is not defined" << endl;
#endif

in myprog.cc. This is an MCVE-fication of my actual case, where the three possible states (1. not defined, 2. defined and null, 3. defined and not null) produce different results. In my actual case, I only needed to distinguish #1 vs. #2 (then the question), but I could turn all my #2 cases into #3 cases so now Octave also knows about it. The downside is that this was deployed across several computers, so instead of writing the Octave code that would handle this right away, I considered changing handling as described above. I am not sure this will not have side effects...

1 Answers

@sancho.sReinstateMonicaCellio, If you don't have a specific use case then this is either a XY problem (see http://xyproblem.info) or you're wasting people's time by writing a misleading question that boils down to "Shouldn't GNU Octave provide a way to determine if an env var is defined?" See https://octave.org/doc/v4.0.1/Environment-Variables.html.

I can't speak to why the GNU Octave developers did not provide a mechanism for determining if an env var is not defined. But I'll bet it has a lot to do with the general design of the language.

You wrote "I would like my script to work irrespective of the host OS and shell.". The problem is that your question is independent of the host OS and shell. The problem is that GNU Octave apparently does not provide an API for distinguishing whether an env var is unset or set to an empty string. That has nothing to do with the OS or shell from which you launched GNU Octave.

Related