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

时间:2017-10-18 10:22:03

标签: bash multiline

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

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

是否有可能以某种方式将其拆分为类似于使用\拆分单独参数的方式。

我试过了:

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

但这不起作用。

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

2 个答案:

答案 0 :(得分:21)

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

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

然后只使用变量:

mycommand "$long_arg"

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

答案 1 :(得分: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

当你用双引号封装它时,它会尊重你的反斜杠并忽略下面的字符,但是因为你用引号将整个事物包裹起来,它会让它认为是引号内的整个文本块应被视为单个参数。