Bash – Getting the first file in a directory in bash

bashshell-script

How do you get the first file in a directory in bash? First being the what the shell glob finds first.

My search for getting the first file in a directory in bash brought me to an old post with a very specific request. I'd like to document my solution to the general question for posterity and make a place for people to put alternative solutions they'd like to share.

Best Answer

To get the first file in the current dir you can put the expansion in an array and grab the first element:

files=(*)
echo "${files[0]}"
# OR
echo "$files" # since we are only concerned with the first element

Assuming your current dir contains multiple dirs you can loop through and grab the first file like so:

for dir in *; do
    files=($dir/*)    
    echo "${files[0]}"
done
Related Question