Foreach command not working with zsh shell on macOS Catalina

Hi MRtrix experts,

I’m currently having difficulty executing scripts using the ‘foreach’ batch command on my zsh shell for macOS Catalina (Version 10.15.2)

For example, when importing my diffusion dicom files into a single ‘dwi.mif’ file:

foreach subjects * : mrconvert IN/MY_DICOM_FOLDER IN/dwi.mif

I get the following output: zsh: parse error near `*’

I’m using the latest version of mrtrix3 as per the documentation.

Many Thanks,
Mervyn Singh

I don’t have a Mac, so I’m not sure I can help much here. But just a couple of suggestions:

  • should there be a space between subjects and *? Maybe there simply isn’t a single file called subjects, so there’s nothing to match?

  • does this command work if you run it on bash (assuming it’s available…)? I.e. just type bash, then try the exact same command again. If that also fails, it’s not because of zsh.

  • list the contents of your current folder with ls, and verify that there are files in there that should match both subjects and a * wildcard.

  • see what the shell actually expands your full command to: add echo at the start of your command, it’ll show you how the shell has actually interpreted your command before running foreach itself.

The issue is that foreach is a shell reserved word in zsh (https://github.com/MRtrix3/mrtrix3/issues/1708). Until we rename the script, you’ll have to use the full path to the script or create an alias for it (alias foreach=$(dirname $(which mrinfo))/foreach). And as Donald mentions, there is a space too many between subjects and *

Hi @jdtournier and @maxpietsch,

Thanks so much for your replies! Apologies for the delayed response, I sent this at the awkward period before the long weekend break here in Aus and did not have the chance to reply until I got back to work :slight_smile:

I did a quick google search and found that there is a method of quickly switching the scripting environment from zsh back to bash:

chsh -s /bin/bash

The original website can be viewed here: How to Change the Default Shell to Bash on macOS Catalina

Once the environment has been switched back to bash, the ‘foreach’ command works as per normal. I have previously been successful with using the foreach command with a space between subjects and *

for example:

foreach subjects * mrdegibbs IN/dwi_denoised.mif IN.dwi_denoised_unringed.mif -axes 0,1

I have been running the 'foreach' command previously on bash with a space in between subjects and * and it seems to be executing fine.

While switching the scripting environment works in the interim, I will also create an alias as per @maxpietsch’s advice ( alias foreach=$(dirname $(which mrinfo))/foreach ) so that I can access the command natively in zsh as well.

Many thanks for your help here!

Best,
Mervyn