0

I am trying to write a bash script to pass a user input string into a Matlab function.

This is the script I currently have:

#!/bin/bash
echo Input a message.
read message
matlab -r -nosplash -nodesktop -nojvm "arduinoWriter\(\'$message\'\);"

where arduinoWriter is a Matlab function that takes a string as an input.

If I run the script and input HELLO , it works as expected. If however I input HELLO WORLD, it does not work. Something about the space is messing it up.

If I run the command matlab -r -nosplash -nodesktop -nojvm "arduinoWriter\(\HELLO\ WORLD\'\);" in the terminal, it works fine, but not if I use HELLO\ WORLD as in the input to the bash script. Even if it did work as an input, I would prefer not to have to put slashes in front of every space.

Any ideas?

1
  • As alternatives, you could use input within MATLAB, or write an M-file script that you execute with matlab -r. Commented Jul 18, 2018 at 3:36

1 Answer 1

2

Your first problem is that you separate the -r parameter and its argument. You need to reorder your command line so that -r appears after the other arguments, and right before the command to execute:

matlab -nosplash -nodesktop -nojvm -r command

(Actually, the order of parameters doesn't matter, but you need to keep -r command together.)

Next, within the double quotes, you don't need to escape the parenthesis or the single quotes:

Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !.

Thus, removing all the backslashes from your command, we get:

matlab -nosplash -nodesktop -nojvm -r "disp('$message');"

(I replaced your function call with something that would actually work on my machine, for testing.)

Sign up to request clarification or add additional context in comments.

1 Comment

Works perfectly now. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.