Bash Scripting – Echo New Line and String Beginning with \t

bashechoquoting

Sure, echo -e can be used so that \n is understood as a new line. The problem is when I want to echo something beginning with \t e.g. "\test".

So let's say I want to perform echo -e "test\n\\test". I expect this to output:

test
\test

But instead outputs:

test
  est

The \\t is being interpreted as a tab instead of a literal \t. Is there a clean workaround for this issue?

Best Answer

echo -e "\\t"

passes \t to echo because backslash is special inside double-quotes in bash. It serves as an escaping (quoting) operator. In \\, it escapes itself.

You can either do:

echo -e "\\\\t"

for echo to be passed \\t (echo -e "\\\t" would also do), or you could use single quotes within which \ is not special:

echo -e '\t'

Now, echo is a very unportable command. Even in bash, its behaviour can depend on the environment. I'd would advise to avoid it and use printf instead, with which you can do:

printf 'test\n\\test\n'

Or even decide which parts undergo those escape sequence expansions:

printf 'test\n%s\n' '\test'

Or:

printf '%b%s\n' 'test\n' '\test'

%b understands the same escape sequences as echo (some echos), while the first argument to printf, the format, also understands sequences, but in a slightly different way than echo (more like what is done in other languages). In any case \n is understood by both.

Related Question