0

Execute the below command and got the output- command=

keytool -list -keystore /etc/pki/java/cacerts -storepass "changeit" | grep _abc_

output=

_abc_sec1, Mar 23, 2021, trustedCertEntry,
_abc_sec2, Aug 30, 2021, trustedCertEntry,

What is the easiest and short way to fetch _abc_sec1 and _abc_sec2 one by one and store in a variable

0stone0
  • 34,288
  • 4
  • 39
  • 64
Mike
  • 25
  • 2
  • `keytool ... | grep -o '_abc_sec[12]'` , the `o` being a GNU extension. – Jetchisel Aug 31 '21 at 14:34
  • 1
    What to you mean by "one by one..."? Storing into an array, concatenate it into a string, or making a loop for using the current value into a variable to be used within the loop? – Pierre François Aug 31 '21 at 14:36
  • 1
    @Mike : What do you mean by _store in a variable_ : Do you want both strings to occur in the same variable (if yes, how should they be separated), or do you want them to end up in an array holding 2 elements? – user1934428 Aug 31 '21 at 14:36

1 Answers1

1

Using cut to get the first column (separated by ,)

We can use the arr=( $(command) ) syntax to parse the output to a bash array.
How do I assign the output of a command into an array?

Then we can easily loop over each substring:

#!/bin/bash

arr=( $(keytool -list -keystore /etc/pki/java/cacerts -storepass "changeit" | grep _abc_ | cut -d',' -f1) )

for ss in "${arr[@]}"; do
   echo "--> $ss"
done

Local example, we're I've placed the 'input' in a text file to mimic the command:

$ cat input
_abc_sec1, Mar 23, 2021, trustedCertEntry,
_abc_sec2, Aug 30, 2021, trustedCertEntry,
something else
$
$
$ cat tst.sh
#!/bin/bash

arr=( $(cat input| grep _abc_ | cut -d',' -f1) )

for ss in "${arr[@]}"; do
   echo "--> $ss"
done
$
$
$ ./tst.sh
--> _abc_sec1
--> _abc_sec2
$
0stone0
  • 34,288
  • 4
  • 39
  • 64