OS Commands in MATLAB

Written by Clarus Goldsmith, 10.17.25

Commands without variables

Putting an exclamation point before a command specifies to MATLAB that it should be run in the OS command line. This is particularly useful for things like opening all needed ports at the beginning of a script.

Example:

!sudo chmod a+rw /dev/ttyUSB0 %Opens the port for the U2D2

The downside of this syntax is it cannot handle using workplace variables.

Commands with variables

Commands that include variables can instead be run using the unix() function:

The overall format of this command is: [status, cmdout] = unix(command_string) where status indicates if the command was run successfully (with 0 being success) and cmdout gives the output from the command, if any. Command inputs should be formatted as a string, so variables can be included using functions like num2str() .

Example:

commitDesc = input('Write commit message: ','s'); %Collects commit description
command = ['git commit -m "' commitDesc '"']; %Combines commit description with the rest of the command
[~, cmdout] = unix(command) %Executes the command

Example with both strategies combined

The following portion of code is from the script used to run Drosophibot II, which can be found in full here. This portion of the script is to automatically push the trial data to my GitHub repository of Drosophibot II data.

%Push to GitHub at the end of the script
cd(savePath)
!git add -A
commitDesc = input('Write commit message: ','s');
command = ['git commit -m "' commitDesc '"'];
[~, cmdout] = unix(command);

Last updated

Was this helpful?