Pass a variable number of bash command line arguments to a MATLAB function

守給你的承諾、 提交于 2019-12-21 20:25:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!