4

Arguments that are passed to a bash script can be passed on to a MATLAB function in the following way:

#!/bin/bash

matlab -nodesktop -nosplash -nodisplay -r "my_function('$1','$2')"

But how to do this if I do not know the number of arguments to pass a priori? So I want to do something like this:

#!/bin/bash

matlab -nodesktop -nosplash -nodisplay -r "my_function('$1',...,'$N')"

where I do not know what number N equals to a priori.

I figure that you could create a string with a for loop containing '$1',...,'$N' and pass the entire string to the above command. But isn't there a more succinct approach?

FIW, I am not fluent in bash. So if the loop is the only way to go, could you please inform me how to do this?

EDIT

I managed to devise a solution to my problem:

#!/bin/bash

INPUT=""
for var in "$@"
do
    INPUT=$INPUT"'"$var"',"
done
INPUT=${INPUT%?}

matlab -nodesktop -nosplash -nodisplay -r "my_function($INPUT)"

Isn't there a easier/shorter way to do this?

3
  • At what point of time you would know the value of N ? Commented Oct 9, 2014 at 16:08
  • Never. The thing is that I am developing a program in MATLAB. The number of input arguments to the main MATLAB function might change over time. And I do not want to modify my bash script that launches my MATLAB program each time I decide to add another input argument. Commented Oct 9, 2014 at 16:14
  • 1
    +1 for the correct spelling - MATLAB instead of matlab which is widely used around here on Stack Overflow. Sorry, no useful comment from me though. Commented Oct 9, 2014 at 16:20

1 Answer 1

3

Taking inspiration from here:

#!/bin/bash

INPUT=$(printf "'%s'," "$@") && INPUT=${INPUT%,}

echo matlab -nodesktop -nosplash -nodisplay -r "my_function($INPUT)"

Output:

$ ./test.sh one two three
matlab -nodesktop -nosplash -nodisplay -r my_function('one','two','three')

It's a little shorter, at least.

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

Comments

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.