How do I negate a test with regular expressions in a bash script?

前端 未结 5 447
名媛妹妹
名媛妹妹 2020-12-12 15:20

Using GNU bash (version 4.0.35(1)-release (x86_64-suse-linux-gnu), I would like to negate a test with Regular Expressions. For example, I would like to conditionally add a p

相关标签:
5条回答
  • 2020-12-12 15:41

    Yes you can negate the test as SiegeX has already pointed out.

    However you shouldn't use regular expressions for this - it can fail if your path contains special characters. Try this instead:

    [[ ":$PATH:" != *":$1:"* ]]
    

    (Source)

    0 讨论(0)
  • 2020-12-12 15:58

    You had it right, just put a space between the ! and the [[ like if ! [[

    0 讨论(0)
  • 2020-12-12 15:59

    You can also put the exclamation mark inside the brackets:

    if [[ ! $PATH =~ $temp ]]
    

    but you should anchor your pattern to reduce false positives:

    temp=/mnt/silo/bin
    pattern="(^|:)${temp}(:|$)"
    if [[ ! "${PATH}" =~ ${pattern} ]]
    

    which looks for a match at the beginning or end with a colon before or after it (or both). I recommend using lowercase or mixed case variable names as a habit to reduce the chance of name collisions with shell variables.

    0 讨论(0)
  • 2020-12-12 15:59

    the safest way is to put the ! for the regex negation within the [[ ]] like this:

    if [[ ! ${STR} =~ YOUR_REGEX ]]; then
    

    otherwise it might fail on certain systems.

    0 讨论(0)
  • 2020-12-12 16:04

    I like to simplify the code without using conditional operators in such cases:

    TEMP=/mnt/silo/bin
    [[ ${PATH} =~ ${TEMP} ]] || PATH=$PATH:$TEMP
    
    0 讨论(0)
提交回复
热议问题