How to assign a glob expression to a variable in a Bash script?

后端 未结 8 1484
渐次进展
渐次进展 2020-12-08 02:21

When the following two lines of code are executed in a bash script, \"ls\" complains that the files don\'t exist:

dirs=/content/{dev01,dev02}
ls -l $dirs
         


        
8条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 02:44

    I suspect that what you need is an array, but that will restrict you to newer bashes. It is saver than using eval.

    dirs=( /"content with spaces"/{dev01,dev02} )
    
    dirs=( /content/{dev01,dev02} )
    ls -l "${dirs[@]}"
    

    /content/{dev01,dev02}
    

    will expand to:

    "/content/dev01" "/content/dev02"
    

    The existence of those directories is irrelevant to the expansion.

    It becomes unpredictable when you assign a variable to a brace expansion.

    dirs=/content/{dev01,dev02}
    

    may turn into

    "/content/dev01"
    

    or

    "/content/dev01 /content/dev02"
    

    or

    "/content/dev01" "/content/dev02"
    

    or

    "/content/{dev01,dev02}"
    

    If you quote the braces in any way they will not expand, so the result will contain the braces and be mostly meaningless.

提交回复
热议问题