Search code examples
bashglob

Pattern matching within a string


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?


Solution

  • 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