Search code examples
bashloopsquotesglobtilde-expansion

bash - looping through directory


I'm having trouble looping through the files in a directory with bash. I'm quite new to bash and can't seem to figure out the issue that I'm having.

When I loop through the files in a directory that I explicitly mention, there doesn't seem to be a problem. However, when a variables is used to describe the directory to loop through, things don't seem to work out.

The working loop, that finds all the files in ~/Desktop/:

for file in ~/Desktop/*; do
    echo "$file"
done

However, the following doesn't seem to work and only displays ~/Desktop/*,

DEST="~/Desktop/*"    

for file in "$DEST"; do
    echo "$file"
done

Hopefully there's something small that I'm missing here. My main goal is that I'd like to be able to loop over an arbitrary location that could be saved within a config file of some sorts.

Thanks in advance!


Solution

  • According to the reference manual, tilde expansion doesn't work in quotes. The easiest alternative is to use $HOME instead.

    Assuming that the code in the question is working apart from the tilde expansion (which is possible if the files in ~/Desktop all have very simple names), then you could amend your code to work without the tilde:

    DEST="$HOME/Desktop/*"    
    
    for file in "$DEST"; do
        echo "$file"
    done
    

    However, you will very likely run into filename expansion (globbing) problems if you do that. You would do best to drop the quotes everywhere, since they're not needed. Also, delay the filename expansion until it is actually needed:

    DEST=~/Desktop
    
    for file in $DEST/*; do
        echo $file
    done