I want my terminal prompt to change color depending on success of the previous command. Currently I achieve this with the following script:
exitstatus()
{
if [[ $? == 0 ]]; then
echo -e "\e[38;5;45mबरें"
else
echo -e "\e[38;5;211mचूक"
fi
}
PS1="\[\e[38;5;252m\][\[\e[38;5;214m\]\A \$(exitstatus)\[\e[38;5;252m\]]> \[\e[0m\]"
Problem here is that echo inside exitstatus doesn't escape colors correctly, leaving some invisible characters. That causes my terminal to cut line short and write the new one on top of the previous when I type long commands.

With PS1 variable I solved this issue by adding \[\] around \e[...m. Echo, however, doesn't have square brackets as escape characters and I can't find a way to make it escape colors correctly.
printfinstead ofecho, but that is always true and not specific to your issue. See Why is printf better than echo?.