Get first file of given extension from a folder

here is the shorter version from your own idea.

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

Here's a way to accomplish it:

for FILE in *.tar.gz; do break; done

You tell bash to break the loop in the first iteration, just when the first filename is assigned to FILE.


Another way to do the same:

first() { FILE=$1; } && first *.tar.gz

Here you are using the positional parameters of the function first which is better than set the positional parameters of your entire bash process (as with set --).


You can use set as shown below. The shell will expand the wildcard and set will assign the files as positional parameters which can be accessed using $1, $2 etc.

# set nullglob so that if no matching files are found, the wildcard expands to a null string
shopt -s nullglob

set -- /path/to/folder/*.tar.gz

# print the name of the first file
echo "$1"

It is not good practice to parse ls as you are doing, because it will not handle filenames containing newline characters. Also, the grep is unnecessary because you could simply do ls /path/to/folder/*.tar.gz | head -1.


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

Tags:

Bash