ajmm
ajmm

Reputation: 23

Problems when listing files with an empty space in the name in a directory using bash

I wanted to have a list of all files inside a directory, because later I am gonna use their names in the code. I used this code

path="directory"
files=($(ls "$path"))
echo "${#files[@]}"
echo "${files[@]}"

Inside the directory I have only one file "file 0". The problem is that the empty space is interpreted as a separation between 2 files. So it prints 2 elements: "file" and "0", as they were 2 different files in the directory.

I couldn't find any question similar to mine. Bash version: GNU bash, version 5.1.16(1)-release Linux mint 21.1

Upvotes: 2

Views: 43

Answers (1)

choroba
choroba

Reputation: 242123

Don't use ls. Use wildcards that are expanded directly by the shell:

path="directory"
files=("$path"/*)

Upvotes: 3

Related Questions