0

I am using a Bash if-else structure based on comparing a variable against a string literal. After reading this Stack Overflow answer and several other suggested Q&As, I tried testing the flow control at the Bash command line:

$ UseMLorRT=MATLAB # Next, test if this choice is properly recognized

$ if [ "$UseMLorRT"="MATLAB" ]; then echo UseMatlab; else echo UseRuntime; fi

   UseMatlab

$ if [ "$UseMLorRT"="Runtime" ]; then echo UseMatlab; else echo UseRuntime; fi

   UseMatlab

The setting UseMLorRT=MATLAB is not being recognized. In the second if-else statement above, echo UseRuntime should be executed, but it is not. I get the same behaviour by comparing using "==" instead of "=" and if I use double square brackets instead of single square brackets.

Can anyone see what I am doing wrong?

user2153235
  • 388
  • 1
  • 11
  • 4
    Please add a valid shebang (`#!/bin/bash`) to your script and remove leading `$`, then paste it at http://www.shellcheck.net/ and try to implement all the recommendations made there. – Cyrus Apr 27 '23 at 18:02
  • 3
    `[ "$UseMLorRT" = "MATLAB" ]` and `[ "$UseMLorRT" = "Runtime" ]`. Notice the spaces around the `=`. – M. Nejat Aydin Apr 27 '23 at 18:03
  • 2
    You are passing only 2 arguments to `[`. The first argument is the string generated by expanding `"$UseMLorRT"="MATLAB"`, and the second argument is `]`. When `[` receives only 2 arguments, it returns 0 if the first argument is not the empty string, and non-zero if the first argument is the empty string. In this case, the argument is guaranteed not to be empty, so `[` returns 0. – William Pursell Apr 27 '23 at 18:06
  • Your suggestions helped. They answer the question. However, I think that the rationale for closing this question is not reasonable. Most people wouldn't know to search for *why* the answer is the way it is unless they *already knew* what the answer was. Thanks for the helpful suggestions, but I ask that the closure of the question be reversed. Perhaps one of the helpful commentators can post the answer and *then* cite the reason for why the answer is the way it is. – user2153235 Apr 27 '23 at 18:19
  • 1
    @user2153235 Actually, that's exactly why this question was closed as a duplicate. Duplicate questions are part of the structure of stackoverflow. Since a single basic problem may appear or be understood in multiple ways, having questions that describe it in all those different ways makes it easier to find a relevant question. But since they're all the same basic problem, it's better to have all of those questions point to a single set of answers. Essentially, a duplicate question functions as a pointer from "how I see the problem" to "what's going on and how to solve it." – Gordon Davisson Apr 27 '23 at 18:45
  • 1
    Ah, OK. Thanks. In that case, my question is providing a service by directing searchers to the "why" question. – user2153235 Apr 27 '23 at 18:57

0 Answers0