bash array operations
sometimes we need to remove one element from an array
for example we remove the element 2 (third) from array
array=(“hello” “i” “like” “bash”)
i=2
array=(${array[@]:0:$i} ${array[@]:$(($i + 1))})










Anonymous said on August 24, 2009
unset command is enough
DemonWeasel said on October 2, 2009
#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 said on October 2, 2009
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 said on October 2, 2009
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]}