Why a variable assignment replaces tabs with spaces

前端 未结 2 1146
轻奢々
轻奢々 2021-01-02 00:42

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
2条回答
  •  旧巷少年郎
    2021-01-02 01:26

    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
    \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
    
    ...
    

提交回复
热议问题