我用这个函数在数组中查找值有一段时间,但我想改进它:
# Checks if the first argument is found in the subsequent ones.
function my_function_is_value_in() {
local -r NEEDLE=$1
local -ra HAYSTACK=( "${@:2}" )
local value
for value in "${HAYSTACK[@]}"; do
[[ $value == "$NEEDLE" ]] && return 0
done
return 1
}
我现在认为对“参数重命名以提高可读性”数组的分配HAYSTACK
效率低下,特别是对于“搜索”功能,可能会这样运行多次:
my_function_is_value_in coconut cherry coriander coconut cottage-cheese
Bash 是否有一种有效的方法来执行上述操作,或者${@:2}
直接循环执行是否尽可能高效?
perl
与's比较/对比grep( /pattern/ @array)
.. 这是一个专门的功能来做到这一点。