Reputation: 179
Directory workspace contains like 5 projects:
project-1
project-2
project-3
project-4
project-5
I want to match all folders in this directory, but the array does not get populated when I use a variable:
workspace="~/workspace";
myDirectories=(${workspace}/project-*/);
If I pass it in manually it picks up the directories without a problem.
myDirectories=(~/workspace/project-*/);
I know it is something simple I am missing, but it is bugging me!
Upvotes: 2
Views: 35
Reputation:
The ~
won't work correctly (expand to user home directory) unless it is unquoted.
As an *
also needs to be unquoted to expand.
You could define the directory as a fixed string (remove the leading ~
):
workspace="workingdirectory" # or just workspace=workingdirectory
And leave all the expansions to the array definition (both work):
myDirectories=( ~/"${workspace}/"project-*/ );
myDirectories=( "${HOME}/${workspace}/"project-*/ );
You may use fixed directories like: "/home/user/$workspace/"project-*/
but in this case you lose the adaptability to any current user running the script without any real gain.
It is also possible to use the ~/
at the time of defining the variable workspace
but that would also fix the user to the user running that part of the script, which may not be the same as the one doing the directory expansions.
All considered, expanding at the time of creating the array seems to b ethe best solution, and both solutions above work well.
Upvotes: 1
Reputation: 42117
You have used quotes in workspace
variable declaration like:
workspace="~/workspace"
So the ~
won't be expanded as the home directory, but would be treated literally.
You can:
Leave ~
outside quotes (note that, quotes are not strictly necessary in this case):
workspace=~/"workspace"
Or use $HOME
instead of ~
:
workspace="$HOME"/workspace
Or use absolute paths starting with /
e.g. /home/username/workspace
Upvotes: 3