I can not find any mention of card expiry on both official and unofficial websites nor in the rules. Likely you will be able to use your cards even coming back after years but I have yet to personally confirm this (I must have some 2-3 old cards lying around somewhere). A local friend I asked also supposes that the card does not expire. However user @LorenPechtel in comments suggests that they will become inactive and need to be reactivated after not having been used for a while.
If you intend to come back one day, what I would do is to just take the card with me and use it the next time.
If instead you don't see yourself coming back to Shanghai over the next ten years nor have friends going to pass it on to them, you can ask for a refund of your deposit and balance.
If your ordinary Shanghai Public Transportation Card is complete and clean, it can be recalled and the deposit can be returned to you. The balance on the card can be immediately returned if it is less than CNY 10. If the balance is between CNY 10 and 2,000, invoice should be taken to ask for the return of money; however, a 5% handling fee will be charged.
This can be done here:
Name of metro stations and business hours:
Time: 9:00 - 19:00, Monday - Sunday and holidays;
Metro Line 1: Gongkang Road Station, Hanzhong Road Station, Hengshan Road Station, Jinjiang Park Station
Metro Line 2: Songhong Road Station, Jiangsu Road Station, Century Park Station, Haitiansan Road Station
Metro Line 3: Caoxi Road Station, Zhongtan Road Station, East Baoxing Road Station, North Jiangyang Road Station
Metro Line 4: Yangshupu Road Station