Home > Back-end >  How to script pairwise comparisons in a for loop in zsh using an if statement?
How to script pairwise comparisons in a for loop in zsh using an if statement?

Time:12-03

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:

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: <

CodePudding user response:

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.

  • Related