1

I am iterating through the array in shell script and when condition matches i.e. if found 'b' want to delete that element from the array. I am not using the index position to iterate through. My array has values (a b c)

My code is

for h in $Arr
do 
    echo -e "Value of current element $h.\n"

    if [ $h == "b" ]
    then
        echo -e "Delete it\n"

    else
        echo -e "Stay here\n"
    fi
done

How can I delete 'b' when condition matches so that when I print my array it should print (a c) ??

1 Answer 1

1

You could build a temp array Brr with the accepted values, then assign Arrwith its value?

Arr=" a b c"
Brr=""
for h in $Arr
do
  echo -e "Value of current element $h.\n"
  if [ $h == "b" ]
  then
    echo -e "Delete it\n"
    #do not add it to Brr
  else
    echo -e "Stay here\n"
    # add it to Brr the temp array
    Brr="${Brr} $h"
  fi
done
Arr="${Brr}"
echo $Arr
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.