Eponymous
Eponymous

Reputation: 129

Use * in bash script

There are more than a few questions about this, but I can't seem to get it right.

I've got a script that assigns a particular path to a variable and adds a filename with an * in it. If the path has a space in it, I can't get the script to evaluate correctly.

Let's say the variable is set to something like:

var="/path/with/a space/in/it/"*.jpg

if I try something like

for i in $var
do
  echo "$i"
done

the script won't find any files at all and will just spit back out the value of var with the * in it, split into two at the space:

/path/with/a
space/in/it/"*.jpg

So is there a way to get it to process the variable as a proper path?

This was some help, but it doesn't quite work as I'd like.

Upvotes: 0

Views: 415

Answers (1)

Ry-
Ry-

Reputation: 225273

Since this is bash, you can make var an array (see this Unix.SE question on expanding globs):

shopt -s nullglob

var=("/path/with/a space/in/it/"*.jpg)

for i in "${var[@]}"
do
  echo "$i"
done

Upvotes: 3

Related Questions