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.

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

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

| improve this answer | |
  • 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. – Gordon Davisson May 26 '18 at 20:31
  • 2
    Also globbing and quotes are done my the shell, ls knows nothing about them. – ctrl-alt-delor May 26 '18 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 '18 at 11:07

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

ls "/dev/sd${device}"*
| improve this answer | |

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.