Reputation: 15
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.
Upvotes: 1
Views: 485
Reputation: 58978
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"
:
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.grep
exits with code 0 if it finds a match.--quiet
to just exit as soon as it finds a match, without printing it.if
just checks whether the command after it returns exit code zero. [[
is just another command, like grep
.grep
) make it obvious what the command is doing, rather than obscuring it.echo
(or cat
, another often abused command) to send things to standard input of commands. A here string is handy for this case.Upvotes: 1