检查 Bash 数组是否包含另一个数组中的值

问题描述 投票:0回答:1
接着

这个问题,如何使用 Bash 来检查一个数组是否包含另一个数组中的值?

出现这种情况的原因是因为我想将用户可用的命令列表放入数组中,然后根据我的脚本的依赖项进行检查,作为在继续之前测试“环境已准备就绪”的一种方法。我使用

compgen

 的原因是因为它是内置的,并且也可以在具有监狱外壳的共享主机上使用。

这是我所拥有的:

#!/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
它似乎有效,但是阅读有关

IFS

等的其他答案,我在这里错过了什么?或者如何改进方法,坚持使用纯 Bash?

arrays bash pattern-matching
1个回答
0
投票
使用关联数组可能更好(bash >= 4):

#!/bin/bash #!/bin/bash required_commands=( grep sed rsync find something-to-fail ) declare -A missing_commands for cmd in "${required_commands[@]}" do missing_commands["$cmd"]= done while IFS='' read -r cmd do unset missing_commands["$cmd"] done < <(compgen -c) if (( ${#missing_commands[@]} != 0 )) then echo "missing commands: ${!missing_commands[*]}" >&2 exit 1 fi
    
© www.soinside.com 2019 - 2024. All rights reserved.