By far the simplest solution, if you are using bash
:
printf %b "$foo"
Or, to save it in another variable name bar
:
printf -v bar %b "$foo"
From help printf
:
In addition to the standard format specifications described in printf(1) and printf(3), printf interprets:
%b expand backslash escape sequences in the corresponding argument %q quote the argument in a way that can be reused as shell input %(fmt)T output the date-time string resulting from using FMT as a format string for strftime(3)
There are edge cases, though:
\c terminates output, backslashes in \', \", and \? are not removed, and octal escapes beginning with \0 may contain up to four digits