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

问题描述 投票:18回答:2

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

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

是否有可能以类似于使用\拆分单独参数的方式拆分它。

我尝试过:

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

但是这不起作用。

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

bash multiline
2个回答
26
投票

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

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

然后只使用变量:

mycommand "$long_arg"

用双引号引起来的新行将被反斜杠删除。请注意,字符串中的所有其他空格都是有效的,即它将出现在变量中。


2
投票

您是否尝试过不使用引号?

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

$ foo "1 \
2 \
3"

1-1 2 3
2-
3-

$ foo 1 \
2 \ 
3

1-1
2-2
3-3

当您将其用双引号引起来时,是用您的反斜杠表示的,并忽略了以下字符,但是由于您将整个内容包装在引号中,因此,它认为应将引号内的整个文本块视为一个参数。


0
投票

我认为应该删除反斜线。

© www.soinside.com 2019 - 2024. All rights reserved.