Search code examples
bashshellsh

How to do conditional decoding of string in shell script


I am working on an API call that gets me back the latest revision number, it will generate either UUID(4e2cab57b35a098993cbaec2455add) or a date formatted string line (2023-03-23T04%253a38%253a09Z).

I would have to apply decode logic to the revision number only when it is generated in date format but not in UUID format and the conversion would be lo 2023-03-23T04%253a38%253a09Z to 2023-03-23T04:38:09Z

Can someone please help me with this.


Solution

  • If you don't want to limit yourself to bash-only, you might want to consider using sed or awk. Both tools already support conditional replacements, but you could use the case statement in your shell, if you need to perform additional actions conditionally.

    revision=....
    
    case "$revision" in
      *-*T*Z) # perform date conversion
        revision="$(printf '%s' "$revision" | sed 's/%253a//g')"
        ;;
      *) # handle everything else, e.g. UUIDs
        ;;
    esac