Testing Bash variable to decide whether to use MATLAB or Runtime

4 次查看(过去 30 天)
I am using a Bash script to test a Java package created from an m-file function using Compiler SDK. I want the script to use either Matlab, if it is installed, or the Matlab Runtime if the former is not installed.
Based on the Stack Overflow answer https://stackoverflow.com/a/17157187, 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?
  2 个评论
Walter Roberson
Walter Roberson 2023-4-27
https://linuxize.com/post/bash-case-statement/ you could use a case statement
FM
FM 2023-4-27
That might be cleaner than assuming that assuming that if $UseMLorRT is set to anything other than MATLAB, then it was set to Runtime (for example, what if it was set to the uncapitalized "matlab" instead?).
I'll possibly look into that in the future. For now, my situation doesn't really allow for that. I've already spent a good portion of the day figuring out the nuances of logical testing in Bash, how to compare variables against string literals, and also trying to learn whether there is a difference between a variable that has not been set versus one that was set to an empty string.
I think it depends on one's role. If I was a developer, I definitely should allot my time accordingly. Since I am not, doing so is very problematic, much as it would help. I appreciate the suggestion nevertheless.

请先登录,再进行评论。

采纳的回答

FM
FM 2023-4-27
编辑:FM 2023-4-27
The answer is that I need spaces not just around the square brackets, but also around the equality test:
#!/bin/bash
# The 2nd statement overrides the 1st
UseMLorRT=Runtime
UseMLorRT=MATLAB
echo UseMLorRT = "$UseMLorRT"
#if [[ "$UseMLorRT"=="Runtime" ]]
if [ "$UseMLorRT" = "MATLAB" ]
then
echo UseMATLAB
else
echo UseRuntime
fi
If UseMLorRT=Runtime comes 2nd above, then the script prints UseRuntime. If `UseMLorRT=MATLAB` comes 2nd, then the script prints UseMATLAB.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Data Type Identification 的更多信息

标签

产品


版本

R2023a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by