Reputation: 1297
While reading about Escape characters
in shell I tried an example -
echo "The balance for user $USER is: \$5:00"
and it gave the output
The balance for user me is: $5.00
But when I tried using the escape character \
with a tab \t
or a newline \n
, it didn't seem to work. I tried using it in double quotes (escape characters retain their meaning in the double quotes) but it still didn't work.
echo "The balance for user $USER is:\t\$5:00"
doesn't give the output
The balance for user me is: $5:00
Instead the output was -
The balance for user vyadav is:\t$5:00
Upvotes: 3
Views: 92
Reputation: 785611
echo
command doesn't expand backslash escapes without -e
option.
You can use echo -e
(please note that this is a gnu extension and not very portable):
echo -e "The balance for user $USER is:\t\$5:00"
The balance for user anubhava is: $5:00
As per help echo
:
-e enable interpretation of the following backslash escapes
Or better to use printf
:
printf "The balance for user %s is:\t\$%s\n" "$USER" "5:00"
Or
printf 'The balance for user %s is:\t$%s\n' "$USER" "5:00"
The balance for user anubhava is: $5:00
Upvotes: 3
Reputation: 81012
There is a difference between what \$
is doing and what \t
is doing.
The shell is expanding variables in double-quoted strings when it sees $
so you need to "escape" the $
from the shell (that's what \$
is doing). You can also use a single-quoted which doesn't expand variables.
\t
on the other hand is "backslash escape" (to use the term the echo
man page uses). There's nothing special about \t
(in a double-quoted string) to the shell so it doesn't touch it. And, by default, echo doesn't process "backslash escapes". You need the -e
flag to turn that on.
Many people think that echo
with arguments is an abomination and shouldn't exist and using the -e
flag is easily avoided by using printf
instead (which does handle a number of "backslash escapes" in its format string).
So the printf
version of this would be (note the lack of \$
in the format string because of the single quotes).
printf 'The balance for user %s is:\t$5:00' "$USER"
Upvotes: 2