This works from the terminal:

ls /dev/sda*

I want it in a bash script, using a variable. I tried:

ls "/dev/sd"$device"*"

But I get the error: ls: cannot access '/dev/sda*': No such file or directory.

2 Answers 2

ls /dev/sd$device* # or
ls "/dev/sd$device"*

You must not quote the globbing metacharacters if you want globbing to be performed.

  • 2
    The quoting in the original is almost exactly backward. You can't quote wildcards you want expanded; you should quote variable references to prevent unexpected word splitting and wildcard expansion on them; quoting fixed strings that don't contain any shell metacharacters doesn't matter. The original had the wildcard quoted and the variable reference unquoted, both of which should be reversed (as in the second option in this answer). BTW, ls /dev/sd"$device"* would also be fine since /dev/sd/ doesn't contain any metacharacters. May 26, 2018 at 20:31
  • 2
    Also globbing and quotes are done my the shell, ls knows nothing about them. May 26, 2018 at 21:52
  • Amusingly, variable assignment works in such a way that you can write this: device=sda*; ls /dev/$device, and get glob expansion after the variable substitution.
    – alexis
    May 27, 2018 at 11:07
  • How will it work if there is an OR search in the variable value like: device="(a|b)"
    – Learner
    Mar 11, 2021 at 0:07

The double quotes tell the shell to leave the * as-is instead of expanding it. This will work:

ls "/dev/sd${device}"*

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .