简体   繁体   中英

Bash comparing STDERR with a string

I want to get standard error of a command and compare if it contains some string: I've created this script:

SONARQUBE_SCANNER_HOME=/var/lib/sdon
                    if msg=$(/var/lib/dtt 2>&1)
                    then
                    echo "Command has is working fine!"
                    else
                      if [[ "$(echo $msg | grep -i 'No such file or directory')" = 'No such file or directory' ]]
                      then
                        echo "Command Path was not found. Not a code issue! Build will now be UNSTABLE!"
                        exit 0
                       else
                        echo "It is something else"
                      fi

                    fi
~

but the ouput is

+ SONARQUBE_SCANNER_HOME=/var/lib/sdon
++ /var/lib/dtt
+ msg='test: line 4: /var/lib/dtt: No such file or directory'
++ echo test: line 4: /var/lib/dtt: No such file or directory
++ grep -i 'No such file or directory'
+ [[ test: line 4: /var/lib/dtt: No such file or directory = \N\o\ \s\u\c\h\ \f\i\l\e\ \o\r\ \d\i\r\e\c\t\o\r\y ]]
+ echo 'It is something else'

As you can see for some odd reason it splits No such file or directory for no reason. The end is just to compare the error of the command to some string, but this seems to fail.

if [[ "$(echo $msg | grep -i 'No such file or directory')" = 'No such file or directory' ]] should be if grep --ignore-case --quiet 'No such file or directory' <<< "$msg" :

  1. grep returns the whole line , including the "test: line 4: /var/lib/dtt: " bit, which is not equal to the text you're looking for in the [[ command. You can use --only-matching to print only the part of the line matching the regex.
  2. grep exits with code 0 if it finds a match.
  3. Since you don't need to print the match (and to speed up existence checks in larger inputs), you can use --quiet to just exit as soon as it finds a match, without printing it.
  4. if just checks whether the command after it returns exit code zero. [[ is just another command, like grep .
  5. Long option names (while not available in all incarnations of grep ) make it obvious what the command is doing, rather than obscuring it.
  6. You very rarely need to use echo (or cat , another often abused command) to send things to standard input of commands. A here string is handy for this case.
  7. Finally, Use More Quotes™ :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM