I have a directory path where there are multiple files and directories.
I want to use basic bash script to create an array containing only list of directories.
Suppose I have a directory path:
/my/directory/path/
$ls /my/directory/path/
a.txt dirX b.txt dirY dirZ
Now I want to populate array named arr[]
with only directories, i.e. dirX
, dirY
and dirZ
.
Got one post but its not that relevant with my requirement.
Any help will be appreciated!
Try this:
#!/bin/bash
arr=(/my/directory/path/*/) # This creates an array of the full paths to all subdirs
arr=("${arr[@]%/}") # This removes the trailing slash on each item
arr=("${arr[@]##*/}") # This removes the path prefix, leaving just the dir names
Unlike the ls
-based answer, this will not get confused by directory names that contain spaces, wildcards, etc.