Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bash xargs script to run parallel MATLAB and Octave jobs
#!/bin/bash
#
# Bash script using xargs to run Matlab and Octave jobs in parallel.
#
n_parruns=16 # Total number of runs.
n_parproc=3 # Number of simultaneous parallel processes.
# Define Matlab/Octave executable and main m-scipt file to run.
export runcmd='/mnt/c/Octave/Octave-4.2.1/bin/octave-cli.exe'
# export runcmd='/mnt/c/Program\ Files/MATLAB/R2017a/bin/matlab.exe -nojvm -nosplash -r'
export mscript=mscript.m
# echo "disp(['test ',num2str(i_parrun)])"$'\npause(5)' > $mscript # Test script.
function parfun
{
echo parproc$1-$$: start # Terminal output.
# Write parproc file to temporary (current) directory.
tempdir=$(pwd)
echo > "$tempdir/parproc$1-$$"
# Octave/Matlab command string.
cmdstr="i_parrun = $1;
$(sed -n '/exit/!p;//q' $mscript)
delete([pwd,filesep,'parproc$1-$$']);"
if [[ $runcmd == *"matlab"* ]]; then
cmdstr="$cmdstr
exit"
eval $runcmd" \"$cmdstr\""
else
echo "$cmdstr" > mscript_$1.m
eval $runcmd" mscript_$1.m"
fi
# Sleep while parproc file exists.
while [ -f "$tempdir/parproc$1-$$" ]
do
sleep 1
done
# Cleanup.
if [[ $runcmd != *"matlab"* ]]; then
rm -f mscript_$1.m
fi
rm -f parproc$1-$$
echo parproc$1-$$: end # Terminal output.
}
export -f parfun
eval "printf \"%i\n\" {1..$n_parruns}" | xargs -n 1 -P $n_parproc -I {} bash -c 'parfun "$@"' _ {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.