I am trying to write a function that removes a value from an array by value. No I do not want to remove it by index.
This is what I've tried so far.
I've seen examples outside of the function. I had to do some wonky shift
thing to pass arguments to finally find the first variable and not loop through the rest and still be able to pass the array.
# Create the array.
LIST=()
LIST+=("one")
LIST+=("two")
LIST+=("three")
# List all the items.
for item in "${LIST[@]}"
do
echo ITEM: $item
done
# Try to define the remove function.
array_remove()
{
FIND=$1 # I'm looking for the first argument.
echo FIND: $FIND
DELETE=($1) # I want to delete this, I've been told to make this also an array....
shift # I have to "shift" to make the rest work.
ARRAY=("$@") # This is the actual second parameter.
for target in "${ARRAY[@]}"; do
for i in "${!ARRAY[@]}"; do
if [[ ${ARRAY[i]} = "${DELETE[0]}" ]]; then
unset 'ARRAY[i]'
fi
done
done
# Now at this point $ARRAY is actually correct, but I want to change $LIST.
"$@"=$ARRAY # How???
}
# Try to remove "two" from the $LIST
array_remove "two" "${LIST[@]}"
# List all the items again, make sure they're removed.
for item in "${LIST[@]}"
do
echo ITEM AGAIN: $item
done
This is not working out. I've tried a lot of things. I don't fundamentally understand how bash works and it's super wonky and unlike any programming language I know (and I knew a few).
The above gives me this.
ITEM: one
ITEM: two
ITEM: three
FIND: two
array.sh: line 25: one: command not found
ITEM AGAIN: one
ITEM AGAIN: two
ITEM AGAIN: three