首页 > 其他分享 >Bash: array contains element

Bash: array contains element

时间:2022-08-15 16:25:43浏览次数:63  
标签:contains number echo four arguments containsElement array local Bash

 

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

 

标签:contains,number,echo,four,arguments,containsElement,array,local,Bash
From: https://www.cnblogs.com/dissipate/p/16588652.html

相关文章