0

This question does not answer my question.

I have a script that checks the existence of specific environment variables and prints them with their values. Now I want to mask the values of password variables (containing SECRET, PW, PASSWORD, KEY in its name, e.g. CLIENT_SECRET) with ****.

Currently I have a script like this:

expected_env_vars=("CLIENT_ID" "CLIENT_SECRET" "BACKEND_KEY" "BACKEND_NAME")

suppress_env_vars_with_substring=("SECRET" "PASSWORD" "PW" "KEY")

for env_var in "${expected_env_vars[@]}"; do
  if [[ -z "${!env_var}" ]]; then
    echo "Environment variable \"$env_var\" not defined"
    exit 1
  else
    # Perform check if an element of $suppress_env_vars_with_substring is substring of $env_var
    echo "$env_var=${!env_var}...OK"
  fi
done

Question
How to check if an array element is substring of a string?

Joe
  • 287
  • 3
  • 13

2 Answers2

1

You may use this script with a grep:

expected_env_vars=("CLIENT_ID" "CLIENT_SECRET" "BACKEND_KEY" "BACKEND_NAME")

suppress_env_vars_with_substring=("SECRET" "PASSWORD" "PW" "KEY")

for env_var in "${expected_env_vars[@]}"; do
  if [[ -z "${!env_var}" ]]; then
    echo "Environment variable \"$env_var\" not defined"
    exit 1
  else
    # Perform check if an element of $suppress_env_vars_with_substring is substring of $env_var
    printf '%s=' "$env_var"
    grep -qFf <(printf '%s\n' "${suppress_env_vars_with_substring[@]}") <<< "$env_var" &&
    echo '****' || echo "${!env_var}"
  fi
done
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

It does not matter, whether or not the operands to be tested belongs to an array or not. The general form is

[[ $x == *$y* ]] && echo "$y is a substring of $x"

You can substitute for $x and $y and parameter expansion you like, including array elements.

user1934428
  • 19,864
  • 7
  • 42
  • 87