5

I am trying to read files from a directory into an array but even when the file doesn't exist, it is saved into the array. I want to exclude the file name if it doesn't exist.

a=(/tmp/nofileexists) && echo ${#a[@]} && echo ${a[@]}
1
/tmp/nofileexists

The path may contain a wild card.

a=(/tmp/nofileexists*.pdf) && echo ${#a[@]} && echo ${a[@]}

1 Answer 1

8

You can use nullglob for bash return empty string when file name expansion fail :

$ shopt -s nullglob
$ a=(/tmp/nofileexists*.pdf) && echo ${#a[@]} && echo ${a[@]}
0
<blank line>

Or using failglob to report error:

$ shopt -s failglob
$ a=(/tmp/nofileexists*.pdf) && echo ${#a[@]} && echo ${a[@]}
bash: no match: /tmp/nofileexists*.pdf
0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.