I'm running a find command that's returning multiple results, but I only need the first result. A bit of googling led me to the "read" command, but I couldn't figure it out, and the man page didn't prove too helpful.

  • Why not just pipe the results to a file? (i.e $ mycommand > myfile.txt)
    – Oxcug
    Aug 8 '14 at 20:19
  • @theMonster - that's not a pipe. That's redirecting the standard output to a file. A pipe would involve... a pipe. '|' e.g. ls -l | head -1 - as answered by Jeff Clayton. Pipes are a pseudo file, though you can make them a file, using mkfifo.
    – JezC
    Aug 9 '14 at 14:14

Enter your command (example: ls -l) then the head command with a pipe like so:

ls -l | head -1
  • 3
    to get the top 10 lines you would change that to head -10 Aug 8 '14 at 20:26
  • in your case it would be this... Aug 8 '14 at 20:27
  • find (command line arguments here) | head -1 Aug 8 '14 at 20:27
  • head -n 10 - ref man head
    – Hannu
    Aug 8 '14 at 20:29
  • 1
    More: head -n -x all but the x last lines, tail -n +x the remainder of the lines, starting at line x - more in the ABS guide referred to in my answer with info on read.
    – Hannu
    Aug 9 '14 at 9:14

You can use the more command to control the amount of text that is shown at a time.

To solve your problem :

Redirect your output to a file you create.

Use For Loop with 1 cycle (counter = 1 , -1 each time). You need to use tokens for search function.

The For Loop will ECHO the first command.

Delete your File.

Store the echo of the FOR Loop in a variable (optional).

I can give some usage definitions if you need it.


How to use read

$ echo -e "1\n2\n3\n4\n5"

$ echo -e "1\n2\n3\n4\n5" | while read n; do  echo "n:$n" ; done


More info on how bash works is available at www.tldp.org in Advanced Bash-Scripting Guide,
there is one more guide on bash Bash Guide for Beginners.


I like lots of ways to tackle unix problems. Here's some others, assuming that command is replaced by whatever it is you're actually doing:

command | awk 'NR == 1 {print}'

command | sed -e 1q

TMP=`mktemp tempXXX`; command > ${TMP} ; ed ${TMP} << HERE

command | split -1 - ; cat xaa ; rm -f x[a-z][a-z]

LINECOUNT=$(command | tee tempfile | wc -l | sed -e 's/ *//g'); \
  tail -$((${LINECOUNT} - 1)) tempfile | diff -u - tempfile | grep '^+' | \
  grep -v '^+++' | sed -e 's/^+//'

If your output is fixed length records (which may be true; example is for 80 characters of input plus a terminal newline):

command | dd ibs=81 count=1

At one point I worked on installing Unix systems from capacity constrained storage devices (floppy disks). We often had to find imaginative ways to use the limited set of commands that we could include on a 1.44MB floppy :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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