Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I need to expand a glob pattern (like ../smth*/*, or /etc/cron*/) into a list of files, programmatically. What would be the best way to do it?

share|improve this question
2  
You don't need to do anything special, just don't quote the *. –  Kevin Mar 12 '12 at 14:32
1  
Though if you're going to be trying to parse it, use an array like the answer says. –  Kevin Mar 12 '12 at 14:34
add comment

1 Answer

up vote 9 down vote accepted

Just let it expand inside an array declaration's right side:

bash-4.2# list=(../smth*/)          # grab the list

bash-4.2# echo "${#list[@]}"        # print array length

bash-4.2# echo "${list[@]}"         # print array elements

bash-4.2# for file in "${list[@]}"; do echo "$file"; done  # loop over the array
share|improve this answer
    
And how do I print that list afterwards? –  Rogach Mar 12 '12 at 13:38
    
It is just a regular array. You can do whatever you can with any array. Added some examples. –  manatwork Mar 12 '12 at 13:44
    
There is a problem. If pattern matches no files, it prints itself - which is not very good. –  Rogach Mar 12 '12 at 14:21
3  
Ah, shopt -s nullglob solves it. –  Rogach Mar 12 '12 at 14:25
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.