Question

I was given a tip to use file globbing in stead of ls in Bash scripts, in my code I followed the instructions and replaced array=($(ls)) to:

function list_files() { for f in *; do [[ -e $f ]] || continue done }
array=($(list_files))

However the new function doen't return anything, am I doing something wrong here?

Was it helpful?

Solution

Simply write this:

array=(*)

Leaving aside that your "list_files" doesn't output anything, there are still other problems with your approach.

Unquoted command substitution (in your case "$(list_files)") will still be subject to "word splitting" and "pathname expansion" (see bash(1) "EXPANSION"), which means that if there are spaces in "list_files" output, they will be used to split it into array elements, and if there are pattern characters, they will be used to attempt to match and substitute the current directory file names as separate array elements.

OTOH, if you quote the command substitution with double quotes, then the whole output will be considered a single array element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top