bashherestring

How can I stop a here string (<<<) from adding a line break or new lines?


It seems that here string is adding line break. Is there a convenient way of removing it?

$ string='test'
$ echo -n $string | md5sum
098f6bcd4621d373cade4e832627b4f6  -
$ echo $string | md5sum
d8e8fca2dc0f896fd7cb4cb0031ba249  -
$ md5sum <<<"$string"
d8e8fca2dc0f896fd7cb4cb0031ba249  -

Solution

  • Yes, you are right: <<< adds a trailing new line.

    You can see it with:

    $ cat - <<< "hello" | od -c
    0000000   h   e   l   l   o  \n
    0000006
    

    Let's compare this with the other approaches:

    $ echo "hello" | od -c
    0000000   h   e   l   l   o  \n
    0000006
    $ echo -n "hello" | od -c
    0000000   h   e   l   l   o
    0000005
    $ printf "hello" | od -c
    0000000   h   e   l   l   o
    0000005
    

    So we have the table:

             | adds new line |
    -------------------------|
    printf   |      No       |
    echo -n  |      No       |
    echo     |      Yes      |
    <<<      |      Yes      |
    

    From Why does a bash here-string add a trailing newline char?:

    Most commands expect text input. In the unix world, a text file consists of a sequence of lines, each ending in a newline. So in most cases a final newline is required. An especially common case is to grab the output of a command with a command susbtitution, process it in some way, then pass it to another command. The command substitution strips final newlines; <<< puts one back.