How can I match a string with a regex in Bash?

后端 未结 6 1152
囚心锁ツ
囚心锁ツ 2020-12-02 05:04

I am trying to write a bash script that contains a function so when given a .tar, .tar.bz2, .tar.gz etc. file it uses tar with the rel

6条回答
  •  情深已故
    2020-12-02 05:33

    To match regexes you need to use the =~ operator.

    Try this:

    [[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched
    

    Alternatively, you can use wildcards (instead of regexes) with the == operator:

    [[ sed-4.2.2.tar.bz2 == *tar.bz2 ]] && echo matched
    

    If portability is not a concern, I recommend using [[ instead of [ or test as it is safer and more powerful. See What is the difference between test, [ and [[ ? for details.

提交回复
热议问题