Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

Is there a simple use of head and cmp (or otherwise) to achieve this?

share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

You can use the exit status of diff and head inside process substitution:

[kbrandt@localhost ~]$ echo arf > foo
[kbrandt@localhost ~]$ echo arf > foo1
[kbrandt@localhost ~]$ diff <(head -n1 foo) <(head -n1 foo1)
[kbrandt@localhost ~]$ echo $?
0
[kbrandt@localhost ~]$ echo foo > foo1
[kbrandt@localhost ~]$ diff <(head -n1 foo) <(head -n1 foo1)
1c1
< arf
---
> foo
[kbrandt@localhost ~]$ echo $?
1
[kbrandt@localhost ~]$ 

Diff compares the files, if the exit status is zero than the files match. Non-zero means they did not match or there was an error running diff which seems unlikely. $? is a shell variable that has the exit status of the previous command. You can redirect the output of diff by adding > /dev/null to the end of the diff command if you don't want to see it on the screen:

[kbrandt@localhost ~]$ diff <(head -n1 foo) <(head -n1 foo1) > /dev/null
[kbrandt@localhost ~]$ echo $?
1
share|improve this answer
    
Thank you Kyle, that's perfect. Process substitution was the concept I was missing. –  StamfordBingo Dec 2 '10 at 15:56
add comment

Here's a way to do it in Bash without using three calls to external utilities. It also works in POSIX shells that don't have process substitution:

read a<file1; read b<file2; [ "$a" = "$b" ]; echo $?

Here's another way using AWK:

awk 'FNR==1{a[NR]=$0; if (NR==2) exit a[1]!=a[2]; nextfile}' file1 file2

Note that AWK comparisons return 1 for true, so I'm using != so the shell gets a 0 which it believes is true.

share|improve this answer
    
+1 -- Always like the bash only solutions :-) –  Kyle Brandt Dec 2 '10 at 22:01
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.