Sleep Yet
Sleep Yet

Reputation: 1

How do I loop through every directory in a given absolute path in linux?

I have a given absolute path such as: /hello/this/is/path/of/directories

My goal is to loop through this absolute path and print each directories name and display information about it in a separate line.

For example looping through the above absolute path would give:

ls-header directory-name

ls information + / (the root)

ls information + hello

ls information + this

ls information + is

ls information + path

ls information + of

ls information + directories

I want to print the ls -d information for each directory in the path and the display the directory name at the end. Right now my code can obtain the absolute path but after that im not sure where to go. If this is too vague please let me know and I can try and specify. Thank you.

Upvotes: 0

Views: 469

Answers (2)

Paul Hodges
Paul Hodges

Reputation: 15408

Assuming you want these in order, I used a sort.

x=/hello/this/is/path/of/directories
ls -d $( while [[ -n "$x" ]]; do echo "$x"; x="${x%/*}"; done | sort )

Upvotes: 0

Shawn
Shawn

Reputation: 52549

One way splits your path into an array of its individual elements and then converts those into complete paths by prepending the previous element of the array to each element in turn, starting with the second:

#!/usr/bin/env bash

show_path() {
    local -a paths
    IFS=/ read -r -a paths <<<"$1"
    local i
    for (( i = 1; i < ${#paths[@]}; i++ )); do
        paths[i]="${paths[i-1]}/${paths[i]}"
    done
    paths[0]=/
    ls -d "${paths[@]}"
}


show_path /hello/this/is/path/of/directories

Upvotes: 1

Related Questions