我想制作一個腳本,當用戶輸入無窮無盡的新行(用回車)并且當他點擊點(.)然后輸入時,它會將他的串列輸出到檔案中。就像“mailx -s”命令一樣。
例如:
Enter names (hit dot (".") to interrupt) :
name1
name2
name3
name4
and so on
.
EOF
我嘗試了以下方法:
read -rp 'Please enter the details: ' -d $'\04' data
declare -p data
存在代碼是 ctrl D,我需要的是點作為檔案的存在代碼。
提前致謝。
uj5u.com熱心網友回復:
不要試圖通過一次閱讀來閱讀所有內容。做一個回圈并檢查每一行。就像是:
#!/bin/sh
content=
while read line && test "$line" != . ; do
content="${content}${line}
"
done
printf "%s" "$content"
uj5u.com熱心網友回復:
我將稍微修改一下 William Pursell 的答案,因為您不妨讀入一個陣列,而不是每次都覆寫相同的字串(即 O(n^2)):
#!/bin/bash
# or use echo if you want the prompt on a separate line
printf 'Please enter the details: '
lines=()
while IFS= read -r line && [[ "$line" != . ]]; do
lines =("${line}")
done
printf '%s\n' "${lines[@]}"
如果您還沒有,請參閱https://mywiki.wooledge.org/BashFAQ/001,它涵蓋了使用IFS=和-r。根據您的確切要求,您可能不想要IFS=。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/398243.html
