1

I am new to shell scripting, I have a script that is used to import cert and import keystore using keytool. This script is inside a Pod, there are times when I have to restart my pod and sometimes when this script runs I get this error

Existing entry alias server exists, overwrite? [no]: Enter new alias name (RETURN to cancel import for this entry):

I know that there is command to list the alias

keytool -list  -keystore keystore.jks -storepass changeit -alias server

which gives the output

server, Jun 22, 2022, PrivateKeyEntry, Certificate fingerprint (SHA-256): AC:DC:12:...

for an alias it that is not there, this command gives an exception

keytool error: java.lang.Exception: Alias does not exist

Is there a way in which I can write a check if the an keystore alias exists, if not allow the keytool -importcert command to execute ? Are there any return codes that I can compare to move forward with the execution ?

Thank you

1 Answers1

0

You can use $? to find the return value of the last executed command.
0 return value means success, otherwise, in case of exception, you get a number other then 0.

keytool -list -keystore keystore.jks -storepass changeit -alias server

if [[ $? = 0 ]]; then
        echo "alias is present"
else
        echo "alias is not present"
fi

EDIT
As Charles Duffy points out the use of $? is discouraged.
You can simply use

if keytool -list -keystore keystore.jks -storepass changeit -alias server; then
        echo "alias is present"
else
        echo "alias is not present"
fi
AddeusExMachina
  • 592
  • 1
  • 11
  • 22
  • 1
    [Why is using `$?` to test if a command succeeded or not an antipattern?](https://stackoverflow.com/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern) – Charles Duffy Jun 22 '22 at 15:31
  • 1
    Instead, just use `if keytoool ...; then echo "alias is present"; else echo "alias is not present"; fi`. – Charles Duffy Jun 22 '22 at 15:32
  • this gives me a result like this: when the alias is present, *server, Jun 22, 2022, PrivateKeyEntry, Certificate fingerprint (SHA-256): AC:05:ED:86 Warning: The JKS keystore uses a proprietary format. It is recommended to migrate to PKCS12 which is an industry standard format using "keytool -importkeystore -srckeystore keystore.jks -destkeystore keystore.jks -deststoretype pkcs12". alias is present *
    When the alias is not there, there is an exception bash-4.2$ ./test.sh *keytool error: java.lang.Exception: Alias does not exist alias is not present*
    – scoutjohn13 Jun 23 '22 at 04:30
  • Have you tried redirecting the output command? ```if keytool ... > /dev/null; then echo "alias is present"; else echo "alias is not present"; fi``` – AddeusExMachina Jun 23 '22 at 06:15