linux - 在 Bash 中将多个用户输入添加到一个变量中

标签 linux bash unix

我对 unix bash 脚本编写相当陌生,需要知道这是否可行。我想多次询问用户输入,然后将该输入存储到一个变量中。

userinputs=   #nothing at the start

read string
<code to add $string to $userinputs>
read string
<code to add $string to $userinputs> #this should add this input along with the other input

所以如果用户在第一次询问时输入“abc”,它会在 $userinputs 中添加“abc”

然后当再次询问输入并且用户输入“123”时,脚本应该将其存储在相同的 $userinputs 中

这将使 $userinput=abc123

最佳答案

在 Bash 中连接两个字符串的常用方法是:

new_string="$string1$string2"

{} 仅在我们有可能阻碍变量扩展的文字字符串时才需要围绕变量名:

new_string="${string1}literal$string2"

而不是

new_string="$string1literal$string2"

您还可以使用 += 运算符:

userinputs=
read string
userinputs+="$string"
read string
userinputs+="$string"

在这种情况下,双引号 $string 是可选的。


另见:

关于linux - 在 Bash 中将多个用户输入添加到一个变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47665217/

相关文章:

regex - 用于查找此格式数字 num :num:num:num 的数字的正则表达式

bash - 为什么正确的 shell 脚本会给出包装/截断/损坏的错误消息?

linux - 如何使用shell脚本删除文本文件中具有相同单词且数字连续增加的字符串?

bash - 带有 Okta 的 Gitlab 访问 token

linux - BASH getopts 可选参数

regex - 如何编写执行以下操作的 grep 函数?

linux - 如何通过查看文件名的一部分来移动文件

bash - 使用 awk 从标准输入或文件中读取

linux - 从/proc 中查找网络地址

我可以让 valgrind 忽略 glibc 库吗?