0

I need to perform some tasks if a particular command fails. More specifically need to check if a key exists in rundeck, if not create it else do nothing. I have following:

rd keys info -p keys/finance/password_a
if [ $? -ne 0 ]
then
  rd keys create -p 'keys/finance/password_a' -t 'password' -f ~/rundeck/password_a
fi

rd command exits in 0 if the key exists, or in an error code if it doesn't.

Issue is, this script is part of pipeline provisioning tasks which fails and exists as soon as any command in it fails. So, the execution never reaches the point if [ $? -ne 0 ] and exits right at rd command after emits and non-zero status code.

Is there a way I can detect a command's final status code but still somehow make it emit a success code i.e. 0?

Maven
  • 14,587
  • 42
  • 113
  • 174
  • 1
    Place the process call in the condition part of the if: `if ! rd keys info -p keys/finance/password_a; then` – Ionuț G. Stan Apr 30 '23 at 20:28
  • 1
    A viable option in this case is `rd keys info -p keys/finance/password_a || rd keys create ...` – pjh Apr 30 '23 at 21:16

1 Answers1

1

You can use || or || case when You need to handle different exit codes and do something for each specific code. check this example:

#!/usr/bin/env bash
## this mocks the behaviour you said.
## 'fails and exists as soon as any command in it fails.'
set -e


## function to mock return codes
makeErr(){
  return $1
}

## lets say return code 12 means key is missing and You can safely create your new key
## but anything else means something went wrong and You shouldn't create a new key


for i in 0 12 123 0 1 ; do 
  makeErr ${i} || case ${?} in
    12)
      printf '%s\n' "key is missing"
      ## anything needed to make a new key
      ;;
    *)
      printf '%s\n' "something went wrong, exit code is ${?}"
      ;;
  esac
done

this will create this output:

key is missing
something went wrong, exit code is 123
something went wrong, exit code is 1
Yaser Kalali
  • 730
  • 1
  • 6