How do I expand an array that has a wildcard argument? For example, I would like to list all files starting with a3 :- declaring a as ("a1" "a2" "a3*") doesn't work, but ("a1" "a2" a3*) works (expression vs string ?), but is there a better way to do that?

#/usr/bin/env bash

touch a1 a2 a31 a32

# list files starting with a3

a=("a1" "a2" "a3*") # fails
a=("a1" "a2" a3*) # works

ls "${a[@]}"

rm a1 a2 a31 a32
  • I am wondering if this is a legitimate case where I should not be double-quoting a value.
    – Nishant
    Oct 1 '20 at 17:49
  • 1
    Note that "works" and "fails" is dependent on what you want to do. If you want to run ls on a file called (literally) a3*, then quoting that string is what you need to do. You don't really say what happens and what you want to happen and what the circumstances are (what files are available in the current directory).
    – Kusalananda
    Oct 2 '20 at 6:04
  • Thanks, @Kusalananda. I thought the wildcard was enough to determine the desired output - but you are right - it is better to be clear.
    – Nishant
    Oct 2 '20 at 7:42

In Bash you can combine different quotes and even unquoted strings in the same "word", so I would probably write a=("a1" "a2" "a3"*). That way, for example if a ends up being pulled out as prefix=a, you can simply do a=("${prefix}1" "${prefix}2" "${prefix}3"*).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.