Unset array element and save to file in Bash

#!/bin/bash

X=(2H 4S 10D QC JD 9H 8S)

How do I unset the 10D from this array and save it to a file?

echo ${X[2]} > file

What do you mean by "unset"? Delete the element?

example:

X=(2H 4S 10D QC JD 9H 8S)
>savefile 
end=${#X[*]}
echo "end = $end"
for i in `seq 0 $(( end -1 ))`  # arrays start with element == zero
do  
   echo "$i is = ${X}" 
   if [ "${X}" = "10D" ] ; then     
      echo  "${X}" >> savefile  # to allow multiple "unsets"
      unset  X      
      echo "$i is now unset and is = ${X}"
      echo "    contents of savefile = `cat savefile`"
   fi 
done
1 Like

Thank you for your reply.

In this particular case X represents the computer's hand in a game of crazy 8's. The 10D is the card that the computer has chosen to play for its turn. So I need to remove it from the computer's hand and It will now be the Active card in play.
Once the element is unset, can it still be called ${X[2]}?

Cogiz

Hi,

No, you can't. Because element is removed from array.

See the example:

X=(2H 4S 10D QC)
$ echo ${X[2]}
10D
$ unset X[2]
$ echo ${X[*]}
2H 4S QC

Here X[2] is QC

1 Like

Thank you. It makes more sense now.

Cogiz