Get the result of a command that can return 254 without breaking the pipeline

Hello, I am tryng to do the following

$CHECK_IF_POLICY_EXISTS=`aws iam get-policy --policy-arn "${QUEUE_POLICY_ACCESS_ARN}"`
if [[ $CHECK_IF_POLICY_EXISTS == *"was not found"* ]]; then
  echo "Creating Policy '${QUEUE_POLICY_ACCESS_ARN}'"
  echo "Policy '${QUEUE_POLICY_ACCESS_ARN}' already exists"

The problem is that the command aws iam get-policy can result in an 254 error with a string similar to:

An error occurred (NoSuchEntity) when calling the GetPolicy operation: Policy arn:aws:iam::123456789:policy/policy-name was not found.

With that, the pipeline will break but I do not want this. I always want the string result of the command.

I tried to do

$CHECK_IF_POLICY_EXISTS=`aws iam get-policy --policy-arn "${QUEUE_POLICY_ACCESS_ARN}"` || true

The pipeline will not break but $CHECK_IF_POLICY_EXISTS is not filled with the string result.

It is not clear what shell you are operating in, but for bash I would write something like

CHECK_IF_POLICY_EXISTS=$(aws iam get-policy --policy-arn "${QUEUE_POLICY_ACCESS_ARN}" || true)

echo 'answer was' $CHECK_IF_POLICY_EXISTS

This is a basic solution that uses ‘|| true’ as a way to avoid the error causing the script to terminate, and instead, you get an empty environment variable on an error. A more detailed solution could also use ‘set -e’, but it would be best to read up on that yourself as you know the overall context of how your script needs to operate. This option would allow you to access the exact exit code.

Great, I did

CHECK_IF_POLICY_EXISTS=$(aws iam get-policy --policy-arn "${QUEUE_POLICY_ACCESS_ARN}" 2>&1 >/dev/null) || true

and It works. Thanks.