Bash:将长字符串参数拆分为多行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46807924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:36:48  来源:igfitidea点击:

Bash: split long string argument to multiple lines?

bashmultiline

提问by ccpizza

Given a command that takes a single long string argument like:

给定一个带有单个长字符串参数的命令,例如:

mycommand -arg1 "very long string which does not fit on the screen"

is it possible to somehow split it in a way similar to how separate arguments can be split with \.

是否有可能以某种方式拆分它,类似于如何使用\.

I tried:

我试过:

mycommand -arg1 "very \
    long \
    string \
    which ..."

but this doesn't work.

但这不起作用。

mycommandis an external command so cannot be modified to take single arguments.

mycommand是一个外部命令,因此不能修改为采用单个参数。

回答by Tom Fenech

You can assign your string to a variable like this:

您可以将字符串分配给这样的变量:

long_arg="my very long string\
 which does not fit\
 on the screen"

Then just use the variable:

然后只需使用变量:

mycommand "$long_arg"

Within double quotes, a newline preceded by a backslash is removed. Note that all the other white space in the string is significant, i.e. it will be present in the variable.

在双引号内,以反斜杠开头的换行符被删除。请注意,字符串中的所有其他空格都很重要,即它将出现在变量中。

回答by Eremite

Have you tried without the quotes?

你试过没有引号吗?

$ foo() { echo -e "1-\n2-\n3-"; }

$ foo "1 \
2 \
3"

1-1 2 3
2-
3-

$ foo 1 \
2 \ 
3

1-1
2-2
3-3

When you encapsulate it in double-quotes, it's honoring your backslash and ignoring the following character, but since you're wrapping the whole thing in quotes, it's making it think that the entire block of text within the quotes should be treated as a single argument.

当您将其封装在双引号中时,它会尊重您的反斜杠并忽略以下字符,但是由于您将整个内容括在引号中,因此它认为引号内的整个文本块都应被视为单个争论。