If you are 100% sure that there is only one matching file just replace:
done < $filename
by:
done < *.txt
Of course this will fail if you have zero or more than one matching file. So, it would be better to test first. For instance with:
tmp=$(shopt -p nullglob || true)
shopt -s nullglob
declare -a filename=(*.txt)
if (( ${#filename[@]} != 1 )); then
printf 'error: zero or more than one *.txt file\n'
else
declare -a var
let count=0
while read line; do
var[$count]=$line
((count++))
done < "${filename[0]}"
fi
eval "$tmp"
The shopt
stuff stores the current status of the nullglob
option in variable tmp
, enables the option, and restores the initial status at the end. Enabling nullglob
is needed here if there is a risk that you have zero *.txt
file. Without nullglob
that would store literal string *.txt
in array filename
.
Your loop could be optimized a bit:
declare -a var
while IFS= read -r line; do
var+=("$line")
done < "${filename[0]}"
IFS=
is needed to preserve leading and trailing spaces in the read lines. Remove it if this is not what you want. The -r
option of read
preserves backslashes in the read line. Remove it if this is not what you want. The +=
assignment automatically adds an element at the end of an indexed array. No need to count. If you want to know how many elements you array contains just use ${#var[@]}
as we did to test the length of the filename
array.
Note that storing the content of a text file in a bash array is better done with mapfile
if your bash version is recent enough. See this other question, for instance.