问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/26282962/pass-a-variable-number-of-bash-command-line-arguments-to-a-matlab-function