Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape newline and tabs in bash variable?

I want to create a multilne variable that will be split over several-lines, indenting on each new line (without the indents being displayed). I have tried several ways:

function regprompt {
    case "$TERM" in
        xterm*)
            PS1=$(cat <<-EOF
                    ${blue} \u ${txtrst}on ${cyan}\h${white}\$gitps1 ${blue}\${fill} \
                    ${undgrn}\d \D{%r} ${blue}\
                    \n[ ${yellow}\$newPWD ${blue}] ${txtrst}$ ${blue}
EOF
)
        ;;
        linux*)
            PS1="${green} \u ${txtrst}on ${cyan}\h${white}\$gitps1 ${green}\${fill} \
                 ${undgrn}\d \D{%r} ${green}\
                 \n[ ${yellow}\$newPWD ${green}] ${txtrst}$ ${green}"
        ;;
        screen*)
            PS1="${green} \u ${txtrst}on ${cyan}\h${white}\$gitps1 ${green}\${fill} \
${undgrn}\d \D{%r} ${green}\
                 \n[ ${yellow}\$newPWD ${green}] ${txtrst}$ ${green}"
        ;;
    esac
}

The first option shows the date part (\d \D{%r}) indented, which I only want to show one space (the one before the escape). Everything else on it shows correctly. The second option does the same. The screen option will display correctly, I just want to know if there is a way to keep it organized?

like image 352
bluTaz Avatar asked Dec 02 '25 06:12

bluTaz


1 Answers

If your variables do not need to contain tabs, you can use the single quote (which allows newlines), indent with tabs, and then remove tabs using tr. For example:

var='ab
        cd
                        ef
gh
        ij'
var=$(echo "$var" | tr -d '\t')
echo "$var"

Note that the indentations must be tabs, not spaces for this to work. Unfortunately I don't know how to indicate this in the formatting. This trick will work in a script, but in an interactive shell entering tabs may not be possible because tab is used by readline for tab-completion. If leading spaces do not need to occur in your variable, you could also use spaces, and instead of tr -d '\t' use something like sed -e 's/^ \+//'.

like image 123
Michał Kosmulski Avatar answered Dec 03 '25 20:12

Michał Kosmulski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!