Wednesday, February 2, 2022

[SOLVED] How to export 'ls' command in bash to separate variables

Issue

For example:

List="$(ls ~/Downloads)" 
echo $List

Output will be:

ExampleDirectory Example_Directory ExampleFile

How do I get (after ls):

echo $File1
echo $File2 
echo $File3

To get

ExampleDirectory
Example_Directory
ExampleFile

Like separate ls output to make not just line of text like in $List, but variables $File1, $File2 and $File3. It seems a bit complicated.


Solution

If you want to assign each file (or directory name) in ~/Downloads to a different bash variable, you will have to find different names for these variables. It would be simpler to use a bash indexed array:

$ declare -a List=(~/Downloads/*)

Then, to print them all:

$ printf '%s\n' "${List[@]}"

To print only the first and third one:

$ printf '%s\n' "${List[0]}" "${List[2]}"

To print the number of entries in the List array:

$ printf '%d\n' "${#List[@]}"


Answered By - Renaud Pacalet
Answer Checked By - David Marino (WPSolving Volunteer)