ʞɔı*_*ɔıu 11 arrays bash shell
有没有办法测试数组是否包含指定的元素?
例如,像:
array=(one two three)
if [ "one" in ${array} ]; then
...
fi
Run Code Online (Sandbox Code Playgroud)
Fra*_*ank 22
for循环可以解决这个问题.
array=(one two three)
for i in "${array[@]}"; do
if [[ "$i" = "one" ]]; then
...
break
fi
done
Run Code Online (Sandbox Code Playgroud)
试试这个:
array=(one two three)
if [[ "${array[*]}" =~ "one" ]]; then
echo "'one' is found"
fi
Run Code Online (Sandbox Code Playgroud)
我的.bashrc文件中有一个“包含”的函数:
contains ()
{
param=$1;
shift;
for elem in "$@";
do
[[ "$param" = "$elem" ]] && return 0;
done;
return 1
}
Run Code Online (Sandbox Code Playgroud)
它可以很好地与数组配合使用:
contains on $array && echo hit || echo miss
miss
contains one $array && echo hit || echo miss
hit
contains onex $array && echo hit || echo miss
miss
Run Code Online (Sandbox Code Playgroud)
但不需要数组:
contains one four two one zero && echo hit || echo miss
hit
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7895 次 |
| 最近记录: |