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?

Aeronaelius
  • 1,291
  • 3
  • 12
  • 31
  • At what point of time you would know the value of N ? – Sainath Motlakunta Oct 09 '14 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. – Aeronaelius Oct 09 '14 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. – Divakar Oct 09 '14 at 16:20

1 Answers1

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.

Community
  • 1
  • 1
zerodiff
  • 1,690
  • 1
  • 18
  • 23