1

As title says, I want to add directory names into an array, but can't figure it out how. This is what I have so far:

path=some/path/in/linux

declare -a categ_array

for d in ${path}/*; do
    #strip directory name of the path
     dir_name=${d##*/}

     #add the directory name into array
     categ_array+=("${dir_name}")
done

echo ${categ_array}

This code outputs only 1 directory name (doesn't matter how many directories i have).

3
  • ${categ_array} expands to only the first element of the array. You should use ${categ_array[@]} instead. Also, loop can be replaced with: categ_array=("$path"/*). Commented Nov 20, 2017 at 15:16
  • 1
    @randomir You would want to follow up the initial assignment with categ_array=( "${categ_array[@]##*/") to strip the leading directory name from each element. Or, use pushd "$path"; categ_array=(*); popd to avoid adding it to each element in the first place. Commented Nov 20, 2017 at 15:33
  • @chepner, you're right, I missed the part where OP strips directories. Commented Nov 20, 2017 at 15:36

1 Answer 1

4

You need to use this command to print all directories:

echo "${categ_array[@]}"

Though you can avoid loop and just use:

cd "$path"
categ_array=()
categ_array+=(*/)

examine the results:

declare -p categ_array
Sign up to request clarification or add additional context in comments.

Comments

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.