MATLAB: Can’t I call Unix commands from MATLAB on Mac OS

MATLABpathsetenvunix

I am using MacOS. From the MATLAB command window, if I execute the following command
system('ls')
I get the error
/bin/bash: ls: command not found
But the command "ls" works properly from the Mac terminal. Similarly none of the typical OS commands like
system( who), system( which)
work from the MATLAB Command Window but they work from the terminal. Why can't I call Unix commands from MATLAB on Mac OS?

Best Answer

If you are starting MATLAB from clicking on the MATLAB icon, then the issue might be caused by this, because when you click on the icon, you are not running MATLAB at the terminal: MATLAB is run by launcher, which does not go through a shell login session. Since MATLAB does not source the "bashrc" file, the PATH set in there is not available to MATLAB if started from the launcher. To verify if this is the cause of the issue, you can launch MATLAB from the terminal and then execute the following commands from the MATLAB Command Window to check if the commands can now be run properly:
system('who')
system('which')
system('ls')
If these commands can now be executed properly from the MATLAB Command Window, then to use the system commands from MATLAB, even if you start from clicking the icon you can set the value of the PATH to point to the proper location by executing the following from the MATLAB Command Window:
setenv('PATH', [getenv('PATH') ':/usr/local/bin:/usr/bin:/bin']);
Note that this will set the PATH only for the current session. If after this you can call the system commands properly, then you can add the above command in the "startup.m" file such that every time MATLAB is launched, the command gets executed automatically. Here are the relevant documentation links for your reference: