How to Check Multiple conditions in IF statement?

I wish to check two conditions inside the if statement

Condition 1: The two file contents should be identical // using cmp command for this.
Condition 2: The two filenames should NOT be the same.

This is what i did in vain.

if [[ cmp $entry1 $entry2 && $entry1 != $entry2 ]]; then

where entry1 and entry2 are

ls *.txt | while IFS='' read -r entry1; do
ls *.txt | while IFS='' read -r entry2; do

Getting this error

./test.sh: line 48: conditional binary operator expected
./test.sh: line 48: syntax error near `$entry1'
bash-3.2$ uname -a
SunOS mymac 5.10 Generic_150400-26 sun4v sparc sun4v

Please suggest.

Hi,

You may have to use quotes around the variables like this;

if [[ "$CommandLineParameter" = "$KLParSUMMERY" && "$BACKGROUND" = "false" ]]; then

Due to the spaces in the commands.

Regards

Gull04

I tried with quotes but it is still the SAME ERROR.

if [[ cmp "$entry1" "$entry2" && "$entry1" != "$entry2" ]]; then

Please suggest.

Hi,

Try it like this;

if [[ `cmp "$entry1" "$entry2"` = "$0" && "$entry1" != "$entry2" ]]; then

Regards

Gull04

1 Like

The condition is failing despite two files with the same contents cmp but different filenames != when it should have passed.

Can you please check ?

Hi,

What does the whole script look like?

Gull04

man bash : Command substitution allows the output of a command to replace the command name, i.e will make the command's stdout available for e.g. variable assignment. cmp will not output anything if files are identical, or some explanatory text if not; neither of which you want to (or can) test for. You'd go for the exit code instead. Try

if cmp $e1 $e2 && [ "$e1" != "$e2" ]; then echo same; else echo diff; fi

Trying to assign the entry variables like you showed in post#1 will fail as the while loop reading from a pipe is executed in a subshell that can't return it's variables to the parent shell, resulting in entry1 and entry2 not being set in the parent shell. Try "process substitution" for the ls command, or put ls 's output into a file and read the variables from there.

1 Like

This worked !! Thank you ...