How to split strings over multiple lines in Bash?

前端 未结 11 1155
[愿得一人]
[愿得一人] 2020-11-29 16:35

How can i split my long string constant over multiple lines?

I realize that you can do this:

echo "continuation \\
lines"
>continuation li         


        
11条回答
  •  温柔的废话
    2020-11-29 17:29

    I came across a situation in which I had to send a long message as part of a command argument and had to adhere to the line length limitation. The commands looks something like this:

    somecommand --message="I am a long message" args
    

    The way I solved this is to move the message out as a here document (like @tripleee suggested). But a here document becomes a stdin, so it needs to be read back in, I went with the below approach:

    message=$(
        tr "\n" " " <<- END
            This is a
            long message
    END
    )
    somecommand --message="$message" args
    

    This has the advantage that $message can be used exactly as the string constant with no extra whitespace or line breaks.

    Note that the actual message lines above are prefixed with a tab character each, which is stripped by here document itself (because of the use of <<-). There are still line breaks at the end, which are then replaced by dd with spaces.

    Note also that if you don't remove newlines, they will appear as is when "$message" is expanded. In some cases, you may be able to workaround by removing the double-quotes around $message, but the message will no longer be a single argument.

提交回复
热议问题