Skip to content

Instantly share code, notes, and snippets.

@likohank
Created August 28, 2018 05:10
Show Gist options
  • Save likohank/5dec12b808d6b3577dd9d8b3bb6a22b5 to your computer and use it in GitHub Desktop.
Save likohank/5dec12b808d6b3577dd9d8b3bb6a22b5 to your computer and use it in GitHub Desktop.
shell 判断某个元素是否在数组中,查看某个key是否存在
if [[ " ${array[@]} " =~ " ${value} " ]]; then
# whatever you want to do when arr contains value
fi
------------------------------------------------------
if [[ ! " ${array[@]} " =~ " ${value} " ]]; then
# whatever you want to do when arr doesn't contain value
fi
------------------------------------------------------
if [[ " ${!array[@]} " =~ " ${value} " ]]; then
# whatever you want to do when arr contains value
fi
------------------------------------------------------
${!array[@]} 获取所有的key
${array[@]} 获取所有的value
------------------------------------------------------
Indexed arrays use positive integer numbers as keys.
Shell 的 Array 数组 使用正整数作为key
--------------------
http://wiki.bash-hackers.org/syntax/arrays
array=()
declare -a ARRAY
直接声明的数组不支持 字符串做为索引,只支持正整数作为key。
如要要声明 关系型数组,需要使用
declare -A ARRAY
declare -A ARRAY Declares an associative array ARRAY. This is the one and only way to create associative arrays.
------------------------------------------------------
@zwxbest
Copy link

zwxbest commented Jan 10, 2020

测试后,${array[@]}输出结果以逗号分割,如果数组中确保不会出现逗号,可以用这个。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment