Assign results of globbing to a variable in Bash

前端 未结 4 1686
孤独总比滥情好
孤独总比滥情好 2021-01-01 09:30

My colleague, Ryan, came to me with a bug in his Bash script, and I identified the problem with this test:

$ mkdir ryan
$ mkdir ryan/smells-bad
$ FOO=ryan/sm         


        
4条回答
  •  心在旅途
    2021-01-01 09:38

    The problem is that the glob will only expand if the file "rotten_eggs" exists, because it is included in the glob pattern. You should use an array.

    FOO=( ryan/smells-* )
    touch "${FOO[@]/%//rotten_eggs}"
    

    The FOO array contains everything matched by the glob. The expansion using % appends /rotten_eggs to each element.

提交回复
热议问题