Concatenating strings in bash overwrites them

前端 未结 4 1731
长情又很酷
长情又很酷 2020-12-09 22:33

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

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


        
相关标签:
4条回答
  • 2020-12-09 23:04

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

    for data in $records ;
    do
        data=$(echo "$data" | tr -d '\r')
        test+="$data"
    done
    
    0 讨论(0)
  • 2020-12-09 23:06

    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 IFS variable to split the tokens and add the value to the array.

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

    0 讨论(0)
  • 2020-12-09 23:12

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

    0 讨论(0)
  • 2020-12-09 23:12

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

    Something like

    IFS="\n"
    

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

    0 讨论(0)
提交回复
热议问题