I have following command output
$ /opt/CrowdStrike/falconctl -g --aid | grep 'aid='
aid="fdwe234wfgrgf34tfsf23rwefwef3".
I want to check if there is any string after aid=
(inside ""). If there is any string, command return code should be 0
and if no value return code must be !=0
.
Can someone please help to extend this command to get required output?
Idea is to make sure my bash script to fail if aid=
doesn't has any value.
CodePudding user response:
You can use regex to check whether one or more characters exist inside the double quotes. And, you can use regex capture group to extract that value:
if [[ $(/opt/CrowdStrike/falconctl -g --aid | grep 'aid=') =~ ^aid=\"(. )\"$ ]]; then
aid=${BASH_REMATCH[0]}
echo "aid is $aid"
else
echo "aid not found"
fi
Note that the regex I use is .
which means 1 or more characters, since you require the string to be non-empty. This is in contrast of the usual .*
regex which would have be 0 or more characters.
CodePudding user response:
I don't have falconctl
on my system so to mimic its output I'll use a couple files:
$ head falcon*out
==> falcon.1.out <==
some stuff
aid="fdwe234wfgrgf34tfsf23rwefwef3".
some more stuff
==> falcon.2.out <==
some stuff
aid=""
some more stuff
One grep
idea:
grep -Eq '^aid="[^"] "' <filename>
Where:
-E
- enable extended regex support-q
- run in silent/quiet mode (suppress all output)- the return code can be captured from
$?
Taking for a test drive:
for fname in falcon*out
do
printf "\n############# %s\n" "$fname"
cat "$fname" | grep -Eq '^aid="[^"] "' "$fname"
echo "return code: $?"
done
This generates:
############# falcon.1.out
return code: 0
############# falcon.2.out
return code: 1