MoreFreeze MoreFreeze - 2 years ago 67
Bash Question

Why a variable assignment replaces tabs with spaces

Why does a variable assignment replace tabs with spaces in the shell?

$ cat tmp
a b e c d
$ res=$(cat tmp)
$ echo $res
a b e c d

Answer Source

You need to quote your variable $res for whitespace to be preserved.

$ cat file
a       b e     c       d

$ res=$(cat file)

$ echo $res
a b e c d

$ echo "$res"
a       b e     c       d

From man bash under QUOTING:

Quoting is used to remove the special meaning of certain characters or words to the shell. Quoting can be used to disable special treatment for special characters, to prevent reserved words from being recognized as such, and to prevent parameter expansion.

Each of the metacharacters listed above under DEFINITIONS has special meaning to the shell and must be quoted if it is to represent itself.


\a     alert (bell)
\b     backspace
\E     an escape character
\f     form feed
\n     new line
\r     carriage return
\t     horizontal tab
\v     vertical tab
\\     backslash
\'     single quote
\"     double quote
\nnn   the eight-bit character whose value is the octal value nnn
\xHH   the eight-bit character whose value is the hexadecimal value HH
\cx    a control-x character

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download