Using Matlab to Create Unix Shell Scripts

Post date: May 22, 2009 12:24:51 AM

One use of Matlab I find highly useful is in creating unix shell scripts. Since I'm more fluent in Matlab than in shell scripting, I essentially use Matlab to format and write my shell scripts, which can then be used in the unix shell. This is very helpful when you want to create a batching script on the go and don't have time to really code it out in a unix shell script, when it could be done in less time by just writing it in Matlab code.

In this example, I'm going to make a shell script that essentially batches my creation text files that are the mean timeseries of deep white matter seeds. To extract the timeseries from each seed I'm going to call on the fslmeants script which is an FSL utility that I find handy for ripping out the mean timeseries of seed regions of interest.

% Step 1. Make a file identifier that points to an open .sh script that you'll be writing your script to. You need this in order to start writing text into the shell script you are creating.

fid = fopen('CreateWhiteMatterTS.sh','wt');

% Step 2. Loop over a small set of subjects. While looping, create a string that will be called in unix to rip out the timeseries for each participant

sublist = {'12001','12002','12004'}; % My list of subject IDs to loop over

WhiteMatterSeedFilename = 'WhiteMatterSeed.nii'; % My white matter seed filename

% Now I loop over the three subjects, each time making a new input filename, output filename, and unix string with the correct subject ID

for isub = 1:length(sublist)

infile = sprintf('%s_RestingState.nii.gz',sublist{isub}); % This is the input file name for fslmeants to use

outfile = sprintf('%s_WhiteMatterTS.txt',sublist{isub}); % This is the output file name for fslmeants to use

unixstr = sprintf('fslmeants -i %s -o %s -m %s;',infile,outfile,WhiteMatterSeedFilename); % This is what I'm executing in the shell script.

fprintf(fid,'%s\n',unixstr); % This adds each line to the shell script

end % end my for loop

fclose(fid); % now close the shell script so I can't write anymore into it

% Step 3. Make sure the shell script has the proper read, write, and execute permissions and then run it from the Matlab prompt.

% Notice I put an ! before each unix command. This is how you execute unix commands in the unix shell while in Matlab.

!chmod u+rwx CreateWhiteMatterTS.sh % This will give the user read, write, and execute permissions on the shell script.

!./CreateWhiteMatterTS.sh % This will pass this string to the unix shell and execute the shell script