Find the answer to your Linux question:
Results 1 to 3 of 3
In a bash-script, only the case if a regular expression does not match is relevant. Therefore I used the exclamation mark !. But where to place it? These two work ...
  1. #1
    Just Joined!
    Join Date
    Dec 2010
    Posts
    16

    ! for not matching bash regex

    In a bash-script, only the case if a regular expression does not match is relevant. Therefore I used the exclamation mark !. But where to place it?
    These two work fine, but are they equivalent?

    Code:
    if ! [[ $abc =~ $pattern ]]; then
    or

    Code:
    if [[ ! $abc =~ $pattern ]]; then
    Where is the ! placed more correct?

  2. #2
    Just Joined!
    Join Date
    Jun 2005
    Posts
    3

    Standing on the shoulders of giants

    if [[ ! is the syntax I find in the linux startup scripts, from which I have always copied syntax. There are a lot of ways to write, but I look to them for the correct conventions.

  3. #3
    Linux User Manko10's Avatar
    Join Date
    Sep 2010
    Posts
    250
    [ is just an executable like test (/usr/bin/[) so in the first example you negate the whole evaluation and in the second example just that one expression, so they are not really equivalent.
    Compare these two cases:
    Code:
    if ! [ true -o true  ]; then
        echo 'x'
    fi
    vs.
    Code:
    if [ true -o ! true  ]; then
        echo 'x'
    fi
    The first outputs nothing because the expression is true and completely negated; the second outputs "x" because only the second operand of the expression is negated (true OR not true is still true).
    Refining Linux Advent calendar: “24 Outstanding ZSH Gems

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...