How to split strings over multiple lines in Bash?

前端 未结 11 1187
[愿得一人]
[愿得一人] 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:34

    This probably doesn't really answer your question but you might find it useful anyway.

    The first command creates the script that's displayed by the second command.

    The third command makes that script executable.

    The fourth command provides a usage example.

    john@malkovich:~/tmp/so$ echo $'#!/usr/bin/env python\nimport textwrap, sys\n\ndef bash_dedent(text):\n    """Dedent all but the first line in the passed `text`."""\n    try:\n        first, rest = text.split("\\n", 1)\n        return "\\n".join([first, textwrap.dedent(rest)])\n    except ValueError:\n        return text  # single-line string\n\nprint bash_dedent(sys.argv[1])'  > bash_dedent
    john@malkovich:~/tmp/so$ cat bash_dedent 
    #!/usr/bin/env python
    import textwrap, sys
    
    def bash_dedent(text):
        """Dedent all but the first line in the passed `text`."""
        try:
            first, rest = text.split("\n", 1)
            return "\n".join([first, textwrap.dedent(rest)])
        except ValueError:
            return text  # single-line string
    
    print bash_dedent(sys.argv[1])
    john@malkovich:~/tmp/so$ chmod a+x bash_dedent
    john@malkovich:~/tmp/so$ echo "$(./bash_dedent "first line
    >     second line
    >     third line")"
    first line
    second line
    third line
    

    Note that if you really want to use this script, it makes more sense to move the executable script into ~/bin so that it will be in your path.

    Check the python reference for details on how textwrap.dedent works.

    If the usage of $'...' or "$(...)" is confusing to you, ask another question (one per construct) if there's not already one up. It might be nice to provide a link to the question you find/ask so that other people will have a linked reference.

提交回复
热议问题