Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first file of given extension from a folder

Tags:

bash

I need to get the first file in a folder which has the .tar.gz extension. I came up with:

FILE=/path/to/folder/$(ls /path/to/folder | grep ".tar.gz$" | head -1)

but I feel it can be done simpler and more elegant. Is there a better solution?

like image 285
linkyndy Avatar asked May 02 '14 08:05

linkyndy


1 Answers

You could get all the files in an array, and then get the desired one:

files=( /path/to/folder/*.tar.gz )

Getting the first file:

echo "${files[0]}"

Getting the last file:

echo "${files[${#files[@]}-1]}"

You might want to set the shell option nullglob to handle cases when there are no matching files:

shopt -s nullglob
like image 199
devnull Avatar answered Oct 07 '22 00:10

devnull