Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to script pairwise comparisons in a for loop in zsh using an if statement?

I am running zsh (z shell) on a Mac.

I would like to run pairwise comparisons between all subjects in the list subjects without repeating overlapping comparisons, such as between subject1-subject2 and subject2-subject1. In this example, only the first comparison should be applied by the code.

subjects=(Subject1 Subject2 Subject3 Subject4)
for i in $subjects
do
for j in $subjects
do
if [ $i < $j ]
then
echo "Processing pair $i - $j ..."
fi
done
done

The output I get is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

zsh: no such file or directory: Subject1
zsh: no such file or directory: Subject2
zsh: no such file or directory: Subject3
zsh: no such file or directory: Subject4
zsh: no such file or directory: Subject1
...

What would be the correct operator in if [ $i < $j ] to exclude repeated comparisons? I also tried using if [ "$i" '<' "$j" ] but then I get zsh: condition expected: <

>Solution :

You need to escape the < argument to [ to prevent it from being interpreted as an input redirection:

if [ $i \< $j ]

Or switch to [[, which bypasses regular command parsing.

if [[ $i < $j ]]

The command [ $i < $j ] is equivalent to [ $i ] < $j, with [ being simply another name for the test command, not some kind of shell syntax.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading