1

Here's my script:

#!/bin/sh

result=$((diff <(sort 1.txt) <(sort 2.txt)))
if [[ $result != "" ]]
then
    echo ERROR
else
    echo PASS
fi

I got an error when execute this script:

chk.sh: line 3: diff <(sort 1.txt) <(sort 2.txt): missing `)' (error token is "1.txt) <(sort 2.txt)")

What the reason and how to fix it?

0

1 Answer 1

3

A few points:

  • process substitution (<( ... )) and the extended test syntax [[ ... ]] is not available in sh. You need more advanced shells like bash or ksh for those.
  • $(( ... )) is arithmetic substitution, not command substitution. You need $( ... ) here.
  • Instead of checking the output of diff, you can check the exit status of diff directly in the if condition. You can discard the unused output. (So you don't even need command substitution or [[ ... ]] here.)

And suggestions from the comments:

  • You can avoid negating the condition in if by swapping the if and else blocks
  • You can use the just-as-efficient cmp -s command if all you want to do is check if the files are different.

Combined:

#!/bin/bash

if cmp -s <(sort 1.txt) <(sort 2.txt)
then
    echo PASS
else
    echo ERROR
fi
4
  • Thanks, added both suggestions. Any ideas on avoiding the process substitution without temp files? Commented Jun 26, 2019 at 12:18
  • Thanks~ But still, I got an error : chk.sh: line 3: syntax error near unexpected token `(' It seems " <( " can't be used? Commented Jun 26, 2019 at 12:32
  • Did you change the first line to bash? You're not on a Mac, are you? Commented Jun 26, 2019 at 12:33
  • I found the command is still sh, not bash, bash is ok :) Commented Jun 27, 2019 at 3:39

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.