Search code examples
regexbashshellls

Use file patterns inside a variable to list files [BASH]


I want to list all files in some directories, so I want to create an array of all the directories and list them recursively in a loop. But,

ls /home/user/{*.txt,*.sh}

lists all the files correctly. But when I use

location="/home/user/{*.txt,*.sh}"
ls $location # Error
ls "$location" # Error
ls ${location} # Error

it gives me an error saying no such file exists. Also, the second method is working just fine if there is only location="/home/user/*.sh". Can someone help?


Solution

  • This is because brace expansion is done before variable substitution.

    https://www.gnu.org/software/bash/manual/html_node/Shell-Expansions.html#Shell-Expansions

    Maybe the following workaround can help using extended globs

    shopt -s extglob
    location="/home/user/*.@(txt|sh)"
    ls $location
    

    or

    location="/home/user/@(*.txt|*.sh)"