1

I want to print a structure of a folder with shell script. So it would look like this

File : linux -3.14/COPYING
File : linux -3.14/CREDITS
   Directory : linux -3.14/Documentation
      File : linux -3.14/Documentation/00 - INDEX
      Directory : linux -3.14/Documentation/ABI
         File : linux -3.14/Documentation/ABI/README

and this is my script. The problem is that it prints out all files and folders for the current directory but it will not print for the subfolders. Maybe I do recursion wrong

dirPrint() {
    # Find all files and print them first
    file=$1
    for f in $(ls ${file}); do
        if [ -f ${f} ]; 
            then
                path="$(pwd)/$f"
                echo "File: $path"
        fi
    done

    # Find all directories and print them
    for f in $(ls ${file}); do
        if [ -d ${f} ];
            then
                path="$(pwd)/$f"
                echo "Directory: $path"
                echo "  $(dirPrint "$path")"
        fi
    done
}
if [ $# -eq 0 ]; then
    dirPrint .
else
    dirPrint "$1"
fi

And also what is the difference between using $1, "$1" and "${1}"?

1
  • 1
    My kubuntu don't have tree command. This is an exercise so i don't know if my tutor has tree command in their linux Commented May 7, 2020 at 16:17

1 Answer 1

2

There are various problems in your script. You shouldn't parse the output of ls, iterate over the expansion of a wildcard instead. Always double quote the variables to prevent spaces in filenames from breaking your commands.

#! /bin/bash
dir_find () {
    local dir=$1
    local indent=$2
    for f in "$dir"/* ; do
        printf '%s%s\n' "$indent${f##*/}"
        if [[ -d $f ]] ; then
            dir_find "$f" "    $indent"
        fi
    done
}

dir_find .
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you. And what's meaning of using [[]] here? What is indent?
It's a more modern version of [] that exists in bash. See man bash for help.
[[ -d $f ]] returns true if $f is a directory.
What is indent short for?
$indent stores spaces for indentation.
|

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.