Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
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 $?
[kbrandt@localhost ~]$ echo foo > foo1
[kbrandt@localhost ~]$ diff <(head -n1 foo) <(head -n1 foo1)
< arf
> foo
[kbrandt@localhost ~]$ echo $?
[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 $?
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

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

Your Answer


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.