How to output a multiline string in Bash?

后端 未结 9 1620
忘了有多久
忘了有多久 2021-01-29 18:14

How can I output a multipline string in Bash without using multiple echo calls like so:

echo \"usage: up [--level | -n ][--help][--version         


        
9条回答
  •  隐瞒了意图╮
    2021-01-29 18:51

    Since I recommended printf in a comment, I should probably give some examples of its usage (although for printing a usage message, I'd be more likely to use Dennis' or Chris' answers). printf is a bit more complex to use than echo. Its first argument is a format string, in which escapes (like \n) are always interpreted; it can also contain format directives starting with %, which control where and how any additional arguments are included in it. Here are two different approaches to using it for a usage message:

    First, you could include the entire message in the format string:

    printf "usage: up [--level | -n ][--help][--version]\n\nReport bugs to: \nup home page: \n"
    

    Note that unlike echo, you must include the final newline explicitly. Also, if the message happens to contain any % characters, they would have to be written as %%. If you wanted to include the bugreport and homepage addresses, they can be added quite naturally:

    printf "usage: up [--level | -n ][--help][--version]\n\nReport bugs to: %s\nup home page: %s\n" "$bugreport" "$homepage"
    

    Second, you could just use the format string to make it print each additional argument on a separate line:

    printf "%s\n" "usage: up [--level | -n ][--help][--version]" "" "Report bugs to: " "up home page: "
    

    With this option, adding the bugreport and homepage addresses is fairly obvious:

    printf "%s\n" "usage: up [--level | -n ][--help][--version]" "" "Report bugs to: $bugreport" "up home page: $homepage"
    

提交回复
热议问题