Assign results of globbing to a variable in Bash

前端 未结 4 1649
孤独总比滥情好
孤独总比滥情好 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:43

    I would do it like this:

    for FOO in ryan/smells-*; do
      touch "$FOO"/rotten_eggs
    done
    

    This way $FOO contains the actual directory name, not the glob pattern. If there's more than one match, though, it will only contain the last one after the loop, so the array solution might be better for that case.

提交回复
热议问题