Search code examples
arraysbashpattern-matching

Check if a Bash array contains a value from another array


Following on from this question, how can one use Bash to check if an array contains values from another array?

The reason this comes up is because I'd like to get a list of commands available to a user into an array and then check that against the dependencies for my script, as a way to test the "environment is ready" before continuing. The reason I use compgen for this is because it's a builtin and is also available on shared hosts that have jailshells.

Here's what I have:

#!/bin/bash

readarray available_commands < <(compgen -c)

required_commands=(
  grep
  sed
  rsync
  find
  something-to-fail
)

for required_command in "${required_commands[@]}"; do
  if [[ ${available_commands[*]} =~ ${required_command} ]]; then
    echo "${required_command} found"
  else
    echo "${required_command} not found"
  fi
done

It seems to work, but reading through the other answer about IFS and so forth, what am I missing here? Or how could the approach be improved, sticking with pure Bash?


Solution

  • You don't need compgen as you can directly check the existence of a command with command -v

    #!/bin/bash
    
    required_commands=(
      grep
      sed
      rsync
      find
      something-to-fail
    )
    
    for cmd in "${required_commands[@]}"
    do
        if command -v "$cmd" >&3
        then
            echo "$cmd found"
        else
            echo "$cmd not found"
        fi
    done 3>/dev/null