在 bash 中连接字符串会覆盖它们

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12358814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:15:22  来源:igfitidea点击:

Concatenating strings in bash overwrites them

bash

提问by skerit

I'm parsing query results from a mysql command (with the --table parameter)

我正在解析来自 mysql 命令的查询结果(使用 --table 参数)

local records=`echo "${query}" | $MYSQL -u $MyUSER -h $MyHOST -p$MyPASS --table`

The query is run successfully, and I receive good data.

查询成功运行,我收到了良好的数据。

Then I iterate over this data:

然后我遍历这些数据:

for data in $records ;
do
    test+=$data
done

The code is more extensive, but this is basically it. Bash sees every space as a separator though, and that's a problem for text fields.

代码比较丰富,不过基本就这些了。Bash 将每个空格都视为分隔符,这对于文本字段来说是一个问题。

So I just concatenate them. But when I feed bash this data:

所以我只是将它们连接起来。但是当我输入 bash 这个数据时:

*URL*
host:
test.url.com
pass:
anothertest

http://www.test.com

It concatenates it to something like:

它将它连接到类似的东西:

pass:test.url.com.com

As if it's not concatenating, but overwriting. Is this maybe some carriage return problem?

好像它不是连接,而是覆盖。这可能是回车问题吗?

回答by cweigel

I had the same issue with the stderr output retrieved from the curlcommand. I found that the output contains carriage return that needs to be removed. For the example above this could be done using the trtool:

curl命令中检索到的 stderr 输出也有同样的问题。我发现输出包含需要删除的回车符。对于上面的示例,这可以使用该tr工具完成:

for data in $records ;
do
    data=$(echo "$data" | tr -d '\r')
    test+="$data"
done

回答by fdermishin

Check that you use Unix line endings. Using Windows line endings caused the same behavior for me, overwriting strings.

检查您是否使用 Unix 行结尾。使用 Windows 行结尾对我造成了相同的行为,覆盖了字符串。

回答by a.drew.b

Make sure you're using Bash 3 or later. The +=operator in Bash can be used to manipulate an Array. It will use the current value of the IFSvariable to split the tokens and add the value to the array.

确保您使用的是 Bash 3 或更高版本。+=Bash 中的运算符可用于操作数组。它将使用IFS变量的当前值来拆分标记并将值添加到数组中。

Try: test="$test $data"to concatenate the data

尝试: test="$test $data"连接数据

回答by Stephen Connolly

Have a look at setting the IFS variableif you are seeing issues with line separators.

如果您发现行分隔符有问题,请查看设置IFS 变量

Something like

就像是

IFS="\n"

Also be careful with +=as it can fall back to array manipulation depending on the version of BASH.

还要小心,+=因为它可能会根据 BASH 的版本回退到数组操作。