Check if an alias exist in keystore

Viewed 94

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 Answers

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
Related