Bash Array Operations

Sometimes we need to remove one element from an array. This Tech-Recipes tutorial contains an example.


We can remove element 2 (third) from an array.

array=(“hello” “i” “like” “bash”)
i=2
array=(${array[@]:0:$i} ${array[@]:$(($i + 1))})

The Conversation

Follow the reactions below and share your own thoughts.

4 Responses to “Bash Array Operations”

  1. August 24, 2009 at 1:25 am, Anonymous said:

    unset command is enough

    Reply

  2. October 02, 2009 at 12:48 am, DemonWeasel said:

    #a function to create a new array minus the specified element

    function remel() {
    array=( `eval echo ‘${‘$1″[@]“‘}’` )
    i=$2
    #remove EL from array
    if [ $i -ne 0 ]; then
    array=( ${array[@]:0:$i} ${array[@]:$(($i + 1))} )
    else
    array=( ${array[@]:$(($i + 1))} )
    fi
    echo ${array[@]}
    }

    #to use it:
    arr=( a b c d )
    echo ${arr[@]}
    echo ${arr[1]}
    #to remove element 1 set the array equal to an array of the output
    arr=( `remel arr 1` )
    echo ${arr[@]}
    echo ${arr[1]}

    Reply

  3. October 02, 2009 at 1:32 am, DemonWeasel said:

    or if you want a more standard syntax of taking an array in as a parameter

    function remel(){
    array=( $@ )
    let ind=${#array[@]}-1
    i=${array[$ind]}
    unset array[$ind]
    if [ $i -ne 0 ]; then
    array=( ${array[@]:0:$i} ${array[@]:$(($i + 1))} )
    else
    array=( ${array[@]:$(($i + 1))} )
    fi
    echo ${array[@]}
    }

    #to use it:
    arr=( a b c d )
    echo ${arr[@]}
    echo ${arr[1]}
    #to remove element 1 set the array equal to an array of the output
    arr=( `remel ${arr[@]} 1` )
    echo ${arr[@]}
    echo ${arr[1]}

    Reply

  4. October 02, 2009 at 2:13 am, DemonWeasel said:

    and…here’s the real solution…

    function remel() {
    array=$1
    i=$2
    if [ $i -ne 0 ]; then
    eval “$array”=”( `eval echo ${$array[@]:0:$i} ${$array[@]:$(($i + 1))}` )”;
    else
    eval “$array”=”( `eval echo ${$array[@]:$(($i + 1))}` )”;
    fi
    }

    #to use it:
    arr=( a b c d )
    echo ${arr[@]}
    echo ${arr[1]}
    #now it actually just removes the element…
    remel arr 1
    echo ${arr[@]}
    echo ${arr[1]}

    Reply

Leave a Reply