我正在编写一个安装脚本,它将作为/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
我想将这一长行分成多行,这样每一行都不超过 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
这不起作用,因为它不打印
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
效果也不太好。它在提示后打印一个换行符。添加
-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
我目前的解决方法是
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
我想知道是否有更好的方法。
请记住,我正在寻找/bin/sh
兼容的解决方案。
答案1
首先,让我们使用变量将读取与文本行解耦:
text="line-1 line-2" ### Just an example.
read -p "$text" REPLY
这样问题就变成了:如何将两行赋值给一个变量。
当然,这样做的第一次尝试是:
a="line-1 \
line-2"
这样写, vara
实际上得到了 value line-1 line-2
。
但是您不喜欢这造成的缺少缩进,那么我们可以尝试从此处文档中将行读入 var(请注意,此处文档中的缩进行需要制表符,而不是空格,才能正常工作):
a="$(cat <<-_set_a_variable_
line-1
line-2
_set_a_variable_
)"
echo "test1 <$a>"
但这会失败,因为实际上有两行被写入$a
.仅获取一行的解决方法可能是:
a="$( echo $(cat <<-_set_a_variable_
line 1
line 2
_set_a_variable_
) )"
echo "test2 <$a>"
这很接近,但会产生其他额外的问题。
正确的解决方案。
上述所有尝试只会让这个问题变得更加复杂。
一个非常基本且简单的方法是:
a="line-1"
a="$a line-2"
read -p "$a" REPLY
您的具体示例的代码是(对于任何read
支持的 shell -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
对于所有其他 shell,请使用:
#!/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
答案2
我发现@BinaryZebra 的方法使用变量更清晰,但您也可以按照您尝试的方式进行操作。您只需将换行符保留在引号内即可:
read -p "goat can try change directory if cd fails to do so. \
Would you like to add this feature? [Y|n] " REPLY
答案3
行末尾的反斜杠允许在多行上继续命令,而不是输出中的实际换行符。
例如,你的第一个方法变成了命令
read -p "goat can try change directory if cd fails to do so. " "Would you like to add this feature? [Y|n] " REPLY
我不确定为什么你想读取输出多行,但我只想用于read
提示行和echo
前面的行。
为了使多行代码更具可读性,请勿在行之间关闭/打开引号。
尝试这个:
read -p "goat can try change directory if cd fails to do so. \
Would you like to add this feature? [Y|n] " REPLY
答案4
就这个怎么样:
#!/bin/bash 读-p“你好 世界 这是一个 多线 提示:“提示 回显$提示