2

I have the following value stored in a variable - pattern

$WS/*.asd

In my environment $WS evaluates to valid directory(/home/administrator/dev/workspaces/). There are some .asd files in this directory. I want to expand the pattern variable to all matching .asd files in this directory. However, I've tried the following commands, but neither of them works:

expand "$pattern"
expand: $WS/*.asd: No such file or directory

ls $pattern
ls: cannot access $WS/*.asd: No such file or directory

eval $pattern
/home/administrator/dev/workspaces/a.asd: Permission denied

echo $pattern
$WS/*.asd

I get the pattern as input. Any idea how I can expand the pattern to a list which includes all matching files.

EDIT: Explain the problem in more details

I may get any combination of env-vars and wildcards in any sequence. For example the input may be: /home/$USER/*/$DIR/*.my_extension. The problem is i want to evaluate all env-vars and expand the wildcards.

2 Answers 2

3

Other than eval you can try this find:

pattern='$WS/*.asd'

find "$WS" -name "${pattern##*/}"

EDIT: Based on your edited question, it seems you will have to use:

eval echo "$pattern"
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry, I wasn't explanatory enough. This solution assumes I know how to extract the directory. I may get any sequence of env-vars and wildcards. For example `/home/$USER/*/$DIR/*.my_extension".
Hmm in that case eval echo "$pattern"
Thank you. Really, this works just as I need it to work. Please, edit your answer by putting that into it and I will mark it.
1

You can store all the elements following that pattern in an array:

#!/bin/bash
arr=()
shopt -s nullglob # expand the glob pattern to a null sting if no elements caught
arr+=($WS/*.asd)
shopt -u nullglob # undo the 'shopt -s nullglob'

To print the entries:

for entry in "${arr[@]}"; do
    echo "$entry"
done

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.