如何在源代码中read -p的提示下将一个长字符串分成多行?

Mat*_*ski 29 shell string shell-script newlines bourne-shell

我正在编写一个安装脚本,它将作为/bin/sh.

有一行提示输入文件:

read -p "goat may try to change directory if cd fails to do so. Would you like to add this feature? [Y|n] " REPLY
Run Code Online (Sandbox Code Playgroud)

我想把这条长行分成多行,这样每行都不超过 80 个字符。我说的是脚本源代码中的行;与执行脚本时实际打印在屏幕上的行无关!

我试过的:

  • 第一种方法:

    read -p "oat may try to change directory if cd fails to do so. " \
        "Would you like to add this feature? [Y|n] " REPLY
    
    Run Code Online (Sandbox Code Playgroud)

    这不起作用,因为它不打印Would you like to add this feature? [Y|n]。

  • 第二种方法:

    echo "oat may try to change directory if cd fails to do so. " \
        "Would you like to add this feature? [Y|n] "
    read REPLY
    
    Run Code Online (Sandbox Code Playgroud)

    也不行。它在提示后打印一个换行符。添加-n选项echo没有帮助:它只是打印:

    -n goat oat may try to change directory if cd fails to do so. Would you like to add this feature? [Y|n]
    # empty line here
    
    Run Code Online (Sandbox Code Playgroud)
  • 我目前的解决方法是

    printf '%s %s ' \
        "oat may try to change directory if cd fails to do so." \
        "Would you like to add this feature? [Y|n] "
    read REPLY
    
    Run Code Online (Sandbox Code Playgroud)

我想知道是否有更好的方法。

请记住,我正在寻找/bin/sh兼容的解决方案。

小智 25

首先,让我们使用变量将读取与文本行分离:

text="line-1 line-2"             ### Just an example.
read -p "$text" REPLY
Run Code Online (Sandbox Code Playgroud)

这样问题就变成了:如何将两行分配给一个变量。

当然,第一次尝试这样做是:

a="line-1 \
line-2"
Run Code Online (Sandbox Code Playgroud)

这样写, vara实际上得到了 value line-1 line-2。

但是您不喜欢这造成的缩进不足,那么我们可能会尝试将行从 here-doc 读入 var(请注意,here-doc 中的缩进行需要制表符,而不是空格,正常工作):

    a="$(cat <<-_set_a_variable_
        line-1
        line-2
        _set_a_variable_
    )"
echo "test1 <$a>"
Run Code Online (Sandbox Code Playgroud)

但这会失败,因为实际上将两行写入$a. 仅获取一行的解决方法可能是:

    a="$( echo $(cat <<-_set_a_variable_
        line 1
        line 2
        _set_a_variable_
        ) )"
echo "test2 <$a>"
Run Code Online (Sandbox Code Playgroud)

这很接近,但会产生其他额外的问题。

正确的解决方案。

上述所有尝试只会使这个问题变得更加复杂。

一个非常基本和简单的方法是:

a="line-1"
a="$a line-2"
read -p "$a" REPLY
Run Code Online (Sandbox Code Playgroud)

您的特定示例的代码是(对于任何read支持的外壳-p):

#!/bin/dash
    a="goat can try change directory if cd fails to do so."
    a="$a Would you like to add this feature? [Y|n] "
# absolute freedom to indent as you see fit.
        read -p "$a" REPLY
Run Code Online (Sandbox Code Playgroud)

对于所有其他外壳,请使用:

#!/bin/dash
    a="goat can try change directory if cd fails to do so."
    a="$a Would you like to add this feature? [Y|n] "
# absolute freedom to indent as you see fit.
        printf '%s' "$a"; read REPLY
Run Code Online (Sandbox Code Playgroud)