0

I want to go recursive through my folders and print the folders/files out. This code should work but it only works for the first folder. Then its stop without a error.

#!/bin/bash

dateiDurchsuchen() {
    DATEIEN=($(ls -d $1/*))
    for(( i=0;i<${#DATEIEN[*]};i++ ))
    do 
        echo ${#DATEIEN[*]}
        ELEMENT=${DATEIEN[$i]}
        echo $ELEMENT
        if [ -d $ELEMENT ]
        then    
            dateiDurchsuchen $ELEMENT
        fi
    done
}
dateiDurchsuchen $HOME

2 Answers 2

2

This happens because bash variables are global by default.

You have to explicitly mark them local:

dateiDurchsuchen() {
    local DATEIEN=( "$1"/* )
    local i
    for(( i=0;i<${#DATEIEN[@]};i++ ))
    do
        echo ${#DATEIEN[@]}
        local ELEMENT=${DATEIEN[$i]}
        echo "$ELEMENT"
        if [ -d "$ELEMENT" ]
        then
            dateiDurchsuchen "$ELEMENT"
        fi
    done
}
dateiDurchsuchen "$HOME"

Also note how the redundant ls is removed, and the variables quoted. This is required to handle filenames with special characters.

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

3 Comments

@Schs That was not the problem and your solution does not work. Create a foo/bar/baz/myfile in your home directory and you'll see that myfile doesn't get listed.
Yes sry you're right. It works with your solution. Thanks for your help. Can you say why ls is redundant, so I learn something...
@Schs globs are expanded by the shell, ls -d just lists the input with colors and in columns, neither of which is used here. You could just as well have used array=( $(echo $1/*) ), "print out every filename separated by spaces, capture that output, split it by spaces, and add each element to the array" which is better expressed as array=( "$1"/* ) "put every filename into the array"
0

This works:

#!/bin/bash

dateiDurchsuchen() {
    DATEIEN=($(ls $1/*))
    for(( i=0;i<${#DATEIEN[*]};i++ ))
    do 
        echo ${#DATEIEN[*]}
        ELEMENT=${DATEIEN[$i]}
        echo $ELEMENT
        if [ -d $ELEMENT ]
        then    
            dateiDurchsuchen $ELEMENT
        fi
    done
}
dateiDurchsuchen $HOME

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.