Cat the first file returned by ls command

Last modified: 
Monday, July 2nd, 2018
Topics: 
Bashlscat

Here we use ls -1 to get a list of the directory contents, pipe it to head -n 1 to get one line, and pipe that to xargs cat.

ls -1 | head -n 1 | xargs cat

This might fail if the argument piped to cat is a directory. You could use a more convoluted strategy to prevent this scenario.

ls -p | grep -v / | head -n 1 | xargs cat

Use the ls -t flag to sort the directory by timestamp.

ls -pt | grep -v / | head -n 1 | xargs cat


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.