1

I want to store the each output of ls command in the variable array. I have already tried at arbitrary directory: var=$(ls);echo $var It is storing the whole file names under the directory to the variable.

I also tried other methods but it is storing each word as variable element in the array.

Is there any method to store the name of each file in a directory at different indexes of an array?

1 Answer 1

2

Yes, don't use ls.

Use a glob.

var=(*)
printf '[%q]\n' "${var[@]}"

%q is a bash-ism (as far as I know). %s would work about equallywell there except for with some odder file names.

From the Bash Reference Manual:

%q

Causes printf to output the corresponding argument in a format that can be reused as shell input.
Sign up to request clarification or add additional context in comments.

4 Comments

Now you did it -- where is the q conversion specifier documented? I can find the q (quad) length modifier, but not the conversion specifier?
@DavidC.Rankin Bash-ism as far as I know, I probably should have mentioned that. It is in the man page and bashref.
I totally agree not to use ls. However, for the benefit of the OP and other readers with similar question, it's worth mentioning that var=($(ls)) will work. And maybe a little explanation regarding the syntax var=( list of values ).
@alvits Except it doesn't work if any of the files contain any spaces or shell metacharacters in their names and so it really just shouldn't be done (especially not when a glob works). Talking about the var=(...) syntax could be reasonable but I'm not sure that's usefully relevant here (the OP knows it works, etc.).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.