0

When using the Linux command "ls", I list all of the files in a directory. I am trying to store the results of the command ls in an array in bash, and then I want to be able to print each element of the array out.

This is what I've tried.

> file_array=( $<ls>) )

and

> file_array= 'ls'

I get an error with the first one, and my array with just print out "ls" with the second one.

codeforester
  • 28,846
  • 11
  • 78
  • 104

1 Answers1

2

It's not a good idea to parse the output of ls. If you must do that, the right syntax would be:

files=($(ls))

You can use a glob instead:

files=(*)          # store file names in an array
declare -p files   # show the contents of array

for file in "${files[@]}"; do
  # do something with file
done

In your second statement, you have a space after = which is not the right syntax for assignments.

codeforester
  • 28,846
  • 11
  • 78
  • 104