DISQUS

Tech-Recipes: bash array operations | Bourne shell scripting | Tech-Recipes

  • Anonymous · 2 years ago
    so looking at the tip found here:
    http://www.tech-recipes.com/bourne_shell_script...

    :oops: works as long as you do not try and remove element 0. Look at just this part:
    ${array[@]:0:$i}
    and you will notice the array is rebuilt using items 0 through $i. The 0 will cause element 0 to stay in the array even if i=0
    Does anyone have a better fix than this:
    #remove i from array
    if [ $i -ne 0 ]; then
    array=( ${array[@]:0:$i} ${array[@]:$(($i + 1))} )
    else
    array=( ${array[@]:$(($i + 1))} )
    fi
  • Anonymous · 1 year ago
    #remove i from array
    unset array[$i]
    array=( ${array[@]} )
  • cori_chenxx · 3 months ago
    unset command is enough
  • DemonWeasel · 1 month ago
    #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]}
  • DemonWeasel · 1 month ago
    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]}
  • DemonWeasel · 1 month ago
    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]}