I am calling a MATLAB function with a bash script

matlab -nodesktop -nosplash -nodisplay -r "matlabfunction input1 input2; quit"

I am trying to get a one digit return value from the matlab function, so I can proceed to other routine base on this return value.

  • 1
    is the value in the $? return code, or is it printed to the screen, or?
    – Jeff Schaller
    May 24, 2017 at 19:12
  • Adding to Jeff's comment, echo $? right after you execute your script, gives you the number you want?
    – user34720
    May 24, 2017 at 19:20
  • echo $? prints out 0 no matter what my return value is. I am not sure if I have my syntax wrong. All I did was matlab -nodesktop -nosplash -nodisplay -r "matlabfunction input1 input2; quit" && echo $?
    – ctbird
    May 24, 2017 at 21:03
  • Your are not doing anything wrong, a exit value of 0 means matlab exited without any issues. You need to tell matlab to use a different exit value, but bash will think that matlab crashed if the exit value is non zero and then && will not work.
    – StrongBad
    May 24, 2017 at 21:48
  • If I echo $? before the quit statement, it does print out the right value. matlab -nodesktop -nosplash -nodisplay -r "matlabfunction input1 input2" echo $? How would I save it into a variable? I tried matlab -nodesktop -nosplash -nodisplay -r "matlabfunction input1 input2" status=$(echo $?) And how do I still execute the quit statement to get out of matlab?
    – ctbird
    May 24, 2017 at 21:51

1 Answer 1


You can quit matlab with either quit or exit. They are basically the same except with exit you can specify an exit code. If you are willing to abuse the exit code then you can do something like

matlab -nodesktop -nosplash -nodisplay -r "exit(times(2, 7));" > /dev/null; echo $?

If you are going to do this realize that bash may get upset about non-zero exit codes and you may need some error handling to make sure your function returns an error code that exit can handle.

The other option is to capture the output of matlab and then parse what you want

matlab -nodesktop -nosplash -nodisplay -r "format compact; Answer=times(2, 7), exit" | sed -ne '/Answer =/{n;p}' | sed -e 's/ *//g'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .