2

In bash, the file globbing * doesn't work inside double quotes, but my filename contains whitespace, so I need to double quote filename before passing it to a shell script. How can I do that?

For example

myscript.sh "0$i*.pdf"

where the pdf files may be "01a b.pdf", "02c d.pdf". I use i to store 1 and then 2.

Thanks.

4
  • What makes it answer my question? Or does you understand my question?
    – Tim
    Commented Nov 27, 2020 at 23:40
  • 3
    "You can interpolate globbing with double-quoted strings", i.e., myscript.sh "0$i"*".pdf".
    – Quasímodo
    Commented Nov 27, 2020 at 23:40
  • What is my question?
    – Tim
    Commented Nov 27, 2020 at 23:41
  • 3
    @Tim, I believe your question is clear enough and also I believe that Quasimodo's comments are exactly to the point. Could you please try the command he suggested in above comment and tell us if it works for you?
    – thanasisp
    Commented Nov 27, 2020 at 23:44

1 Answer 1

6

Simply unquote the glob.

myscript.sh "0$i"*".pdf"

It seems you are worried that * would expand to a string containing whitespace, b? That is no problem, after pathname expansion (as known as globbing), whitespace loses its syntatical value and becomes literal.

See a sample execution:

$ ls -1
'01a b.pdf'
'01e f.pdf'
'02c d.pdf'
myscript.sh

$ cat myscript.sh
#!/bin/sh
for file in "$@"; do
    echo "$file"
done

$ i=1

$ ./myscript.sh "0$i"*".pdf"
01a b.pdf
01e f.pdf

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