Reputation: 19677
I am writing a bash script that contained a command similar to:
echo Configure with --with-foo=\"/tmp/foo-*\"
I wanted this command to produce output such as:
Configure with --with-foo="/tmp/foo-1.3.2"
but the pattern wasn't expanded because it was embedded within a string. I got it to work by using command substitution:
echo Configure with --with-foo=\"$(echo /tmp/foo-*)\"
I think this is the standard /bin/sh solution, but does bash support a solution that doesn't require forking a sub-shell, in the same way that $((6 * 7))
can be used in place of $(expr 6 \* 7)
? Also, is there a way to restrict the result to a single match?
Upvotes: 1
Views: 189
Reputation: 36282
As alternative, use a for
loop and break
after first iteration:
shopt -s nullglob
for f in /tmp/foo-*; do
echo "Configure with --with-foo=\"$f\""
break
done
Upvotes: 1
Reputation: 247210
To check how many files your pattern expands into, store the expansion into an array before using it
shopt -s nullglob
foo=(/tmp/foo-*)
if (( ${#foo[@]} == 0 )); then echo "no foo files"
elif (( ${#foo[@]} > 1 )); then echo "too many foo files"
else do something with "${foo[0]}"
fi
Upvotes: 1