Bash: array contains element

 

function containsElement() {
    local n=$#  # number of arguments 
    local value=${!n}  # last of arguments
    
    echo "${@:2}"
    echo "${@:0}"
    echo number of arguments $#
    for ((i=0;i<=$#;i++)) {
        echo $i ${!i}
        if [ "${!i}" == "${value}" ]; then
            echo $value == ${!i}
            #return 0
        fi
    }
    return 2
}

A=("one" "two" "three four")

if containsElement "${A[@]}" one; then
    echo one in ${A[@]}
fi

 

 

 

$0 为脚本文件,$1 - $# 为传递给脚本的参数

 

function containsElement() {
    local n=$#  # number of arguments 
    local value=${!n}  # last of arguments
    
    echo "${@:2}"
    echo "${@:0}"
    echo number of arguments $#
    for ((i=0;i<=$#;i++)) {
        #echo $i ${!i}
        if [ "${!i}" == "${value}" ]; then
            #echo $value == ${!i}
            return 0
        fi
    }
    return 2
}

A=("one" "two" "three four")

if containsElement "${A[@]}" one; then
    echo one in ${A[@]}
fi

 

2: argument1 为待检测元素

function containsElement() {
    for item in "${@:2}"; do
        [[ "$item" == "$1" ]] && return 0
    done
    return 5
}


A=("one" "two" "three four")

if containsElement "three four" "${A[@]}"; then
    echo in
fi

 

3:

function containsElement() {
    local value=$1
    shift
    for item in "${@:1}"; do
        [[ "$item" == "$value" ]] && return 0
    done
    return 5
}


A=("one" "two" "three four")

if containsElement "three four" "${A[@]}"; then
    echo in
fi

 

posted @ 2022-08-15 16:12  ascertain  阅读(24)  评论(0编辑  收藏  举报