I have this bash code:

   local r2g_keep_temp=$(r2g_match_arg "--keep" "${my_args[@]}");
   local r2g_multi_temp=$(r2g_match_arg "--multi" "${my_args[@]}");

   local r2g_multi=[ "$r2g_multi_temp" || "$r2g_keep_temp" ];

I just want r2g_multi to represent a boolean, if either $r2g_multi_temp or $r2g_keep_temp is defined. How can I do that? The above is syntactically invalid.

On the other hand, this is syntactically valid, but not sure if it's correct:

local r2g_multi=$("$r2g_multi_temp" || "$r2g_keep_temp");

There are no booleans in the shell scripts.

Best simulation for them are integer values.
For example, 0 for true and 1 for false.

[[ -v variable_name ]] will return 1 if the variable_name was not defined or 0 if it was.

Therefore, you can get your desired behavior with this:

// If one of the variables is defined, return value of this command is 0.
[[ -v r2g_keep_temp ]] || [[ -v r2g_multi_temp ]]

// Save the return value of the last command (0 or 1).
local r2g_multi="$?"

Of courese, you can interpret the numbers however you like, I just wanted to demonstrate one example.

By the way,

local r2g_multi=$("$r2g_multi_temp" || "$r2g_keep_temp");

is not the thing that you wish.

  1. First the variables r2g_multi_temp and r2g_keep_temp will be replaced by their values.
  2. Now the subshell will try to execute the value of the r2g_multi_temp.
  3. If by some miracle that value is a valid bash command there are 2 cases:
    • That command is executed succesfully and its stdout is saved in the r2g_multi.
    • That command failed and subshell invoked the value of the r2g_multi_temp.
      Similar story again, if it is a valid command it will be executed and its stdout will be appended on the possible stdout of the command executed from the value of r2g_keep_temp and everything will be stored in r2g_multi.

All in all, run away from this :D

| improve this answer | |
  • nice, what's the difference between -n $foo and -v $foo? I just heard of using -n to check if a variable is non empty – Alexander Mills May 7 '18 at 23:27
  • "0" and "1" are both defined though, so I need to return either "" or "1" not "0" and "1" – Alexander Mills May 7 '18 at 23:28
  • 1
    foo="", for this variable -n $foo will return 1 while -v foo (note that there is no $) will return 0. I don't understand the second quetion, can you explain it a bit more? – Iskustvo May 7 '18 at 23:57
  • nevermind, I was just confused between -v -z -n – Alexander Mills May 8 '18 at 0:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.