Shell

如何在源碼中read -p提示符下將長字元串分成多行?

  • January 6, 2021

我正在編寫一個安裝腳本,它將作為/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兼容的解決方案。

首先,讓我們使用變數將讀取與文本行分離:

text="line-1 line-2"             ### Just an example.
read -p "$text" REPLY

這樣問題就變成了:如何將兩行分配給一個變數。

當然,第一次嘗試這樣做是:

a="line-1 \
line-2"

這樣寫, 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>"

但這會失敗,因為實際上將兩行寫入$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支持的外殼-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

引用自:https://unix.stackexchange.com/questions/272353