Search code examples
stringbashconcatenationgit-bash

Bash when i try to apped to a string its overwrite


i run the following function in (git-)bash under windows:

function config_get_container_values() {

local project_name=$1
local container_name=$2

#local container_name="gitea"

echo "###"
buildcmd="jq -r \".containers[]."
echo "$buildcmd"
buildcmd="${buildcmd}${container_name}"
echo "$buildcmd"
buildcmd="${buildcmd}foobar"
echo "$buildcmd"
echo "###"

}

The output of this is the following. Whyever, after using the variable to extend the string, he starts to overwrite $buildcmd. I tried this also with everything in one line as well with the append command (=+). Everytime the same result.

###
jq -r ".containers[].
jq -r ".containers[].gitea
foobar".containers[].gitea
###

The really strange thing is: When i enable the line local container_name="gitea" everything works as expected. The output is:

###
jq -r ".containers[].
jq -r ".containers[].gitea
jq -r ".containers[].giteafoobar
###

When i put this all into a news file, its also works as expected. So i think something goes wrong in the thousands of line before calling this function. Any idea, what could be cause of this behavior?

Regards

Dave


Solution

  • This is not how you should build up the command, DOS line endings aside. Use --arg to pass the name into the filter as a variable. For example,

    config_get_container_values() {
    
      local project_name=$1
      local container_name=$2
    
      jq -r  --arg n "$container_name " '.containers[][$n+"foobar"]'
    }
    
    config_get_container foo gitea < some.json