0

I've been trying to learn Linux shell, and what I'm trying to do is pretty simple: Running a script where it automatically finds all the folders in the current directory and add the folders names dynamically to an array. This is what I've got so far:

#!/bin/bash

currdirectory="$(ls -d */ | sed 's/.$//')" #getting all the folders' names in a string without the '/' at the end
numberLines="$(ls -d */ | sed 's/.$//' | wc -l)" #count the number of output lines

FOLDER_NAMES=() #create the array

for (( i=1; i<=$numberLines; i++ ))
do  
   line="${$currdirectory | sed -n ${i}p}" #adding the output of a current i line to the variable line
   FOLDER_NAMES+=($line) #adding the element itself to the array
done

echo "FOLDER_NAMES: ${FOLDER_NAMES[*]}" #show array values

However, it's not working, all the elements in the array have all the lines, which I don't understand because if I use the

ls -d */ | sed 's/.$//' | sed -n 3p  #3 for example

directly on the shell, it works. I'm probably making a syntax mistake.

  • 2
    `directories=( */ )` -- that's all there is to it. [Don't ever parse `ls`](http://mywiki.wooledge.org/ParsingLs). `"${directories[@]%/}"` will expand to that without the trailing `/`s – Charles Duffy Jun 21 '18 at 20:58
  • BTW, to see what the contents of an array is, `printf '%q\n' "${directories[@]}"` is much more reliable; you could also `declare -p directories`. By contrast to those, `echo "${directories[*]}"` gives you no way to tell the difference between one directory named `name with spaces`, and three separate directories called `name`, `with` and `spaces`. – Charles Duffy Jun 21 '18 at 20:59
  • (...and `${currdirectory | ...}` isn't well-defined syntax; I'm surprised it did anything other than throw an error. Also, please make a habit of fixing bugs that can be identified by http://shellcheck.net/ before asking questions here). – Charles Duffy Jun 21 '18 at 21:02

0 Answers0