matlab execute script from command linux line

In order to run a script you can open Matlab (you can prevent run it without the GUI using -nodisplay and -nodesktop flags), then run the script using the run command, and finally close matlab using exit.

You can do all this from a terminal with a single instruction:

matlab -nodisplay -nosplash -nodesktop -r "run('path/to/your/script.m');exit;"

However Matlab outputs the welcome message to the console before running your script. To get rid of the welcome message just skip the first 11 lines (10 depending on your Matlab version) using tail -n +11

So your final instruction will be:

matlab -nodisplay -nosplash -nodesktop -r "run('path/to/your/script.m');exit;" | tail -n +11

Starting with R2019a, the preferred method would be, for your test.m script:

matlab -batch "test"

This has several advantages, mainly no need for all the -no flags and MATLAB will exit with non-zero status if test.m (must be on search path) contains an error.

From the documentation page, matlab (Linux):

Execute MATLAB script, statement, or function non-interactively. MATLAB:

  • Starts without the desktop
  • Does not display the splash screen
  • Executes statement
  • Disables changes to preferences
  • Disables toolbox caching
  • Logs text to stdout and stderr
  • Does not display dialog boxes
  • Exits automatically with exit code 0 if script executes successfully. Otherwise, MATLAB terminates with a non-zero exit code.

statement is MATLAB code enclosed in double quotation marks. If statement is the name of a MATLAB function or script, do not specify the file extension. Any required file must be on the MATLAB search path or in the startup folder.

Use the -batch option in non-interactive scripting or command line work flows. Do not use this option with the -r option.

To test if a session of MATLAB is running in batch mode, call the batchStartupOptionUsed function.

Example: -batch "myscript"


I created a basic shell script called runm and put in my path:

$ runm mymatlab.m

Script:

# simple script to run matlab script
if [ $# -eq 0 ]
  then
    echo "please pass m script"
fi

matlab -nodisplay -nosplash -nodesktop -r "run('$1');"

Tags:

Linux

Matlab