Bash: Why is echo adding extra space?

后端 未结 7 1963
轻奢々
轻奢々 2021-01-04 11:15

I get:

$ echo -e \"D\"{a,b,c}\".jpg\\n\"
Da.jpg
 Db.jpg
 Dc.jpg

Note: The extra spaces before Db and Dc on the 2nd and 3rd line of the outp

7条回答
  •  清酒与你
    2021-01-04 12:03

    Because that's what brace expansion does. From man bash, under the heading Brace expansion:

    Patterns to be brace expanded take the form of an optional preamble, followed by ... a series of comma-separated strings ... followed by an optional postscript. The preamble is prefixed to each string contained within the braces, and the postscript is then appended to each resulting string, expanding left to right For example, a{d,c,b}e expands into ‘ade ace abe’

    So in your example, "D" is the preamble and ".jpg\n" is the postscript.

    So, after brace expansion occurs, you're left with:

    echo -e Da.jpg\n Db.jpg\n Dc.jpg\n

    As hewgill points out, the shell then splits this into three tokens and passes them to echo; which outputs each token separated by a space. To get the output you want, you need to use one of the many suggestions here that don't re-inserted the unwanted space between tokens.

    It's longer and probably not the neatest way to do this, but the following gives the output you're after:

    for file in "D"{a,b,c}".jpg"
    do
      echo ${file}
    done
    

提交回复
热议问题