It can be achieved with the builtin bash parameter expansion:
#!/bin/bash
keyword1='Serial\s\+Number'
keyword2='Signature\s\+Algorithm'
inbetween='0e:64:c5:fb:c2:36:ad:e1:4b:17:2a:eb:41:c7:8c:b0'
src="$keyword1$inbetween$keyword2"
strip_begin=${src#"$keyword1"}
strip_end=${strip_begin%"$keyword2"}
[ "$inbetween" = "$strip_end" ] && echo "It works" || echo "It doesn't work"
For further details, see bash substring removal.
But in order to simply retrieve the two required fields from above command output, try something like this:
certificate=$(openssl s_client -servername example.com -connect example.com:443 </dev/null 2>/dev/null | openssl x509 -text)
serial_number_key="Serial Number:"
serial_number=$(echo "$certificate" | awk "/$serial_number_key/ "'{ getline; print $0}' | tr -d " ")
echo "$serial_number"
signature_algorithm=$(echo "$certificate" | grep -m1 'Signature Algorithm:')
signature_algorithm=${signature_algorithm##*Signature Algorithm: }
echo "$signature_algorithm"
certificate_content=$(awk '/BEGIN CERTIFICATE/ {flag=1;next;} /END CERTIFICATE/ {flag=0} flag' <(echo "$certificate"))
echo "$certificate_content"
The basic idea is to store the certificate in a variable; then use common Unix tools like grep
, sed
, awk
, cut
, tr
et. al. and shell builtins like parameter expansion to retrieve the individual fields.
There might be a more elegant way if you need to retrieve many more values; but the optimal solution depends on knowing more detailed requirements.