NOTE: I missed a syntax issue in my script that was causing this. I was passing ${bar} as {$bar}. This can be removed or locked or whatever is done with these types of questions.

I'm trying to test a script I am writing. To view the contents of a variable, I'm attempting to echo it from the function it is passed to. When it does, the expanded variable has braces added around it. Any idea why it's doing this and pointers on how I can prevent it? I'm assuming that if I passed the variable to a command, it would include the braces which would likely cause an error. Please correct me if I'm wrong in this assumption. Code is something like this:

  for i in {1..5}; do echo ${!i}; done


editncopy string1 string2 ${foo} ${bar} ${s}

Output is like this:

[me@home dir]$ ./myscript.sh
[me@home dir]$

It's always the $4 variable in the function that adds braces ({username@server:/another/dir/} should be just username@server:/another/dir/). I tried echoing it on its own (echo $4), but it didn't matter.

In a nutshell, the script is going to modify the contents of another script using sed, then copy it out to other servers using scp.

  • 1
    I do not get that result (and you shouldn't). What shell are you working with? Is that your actual code? It isn't the actual output of that code. – Michael Homer Feb 22 '18 at 19:12
  • Extra braces around the parameter during the call to the function? – Jeff Schaller Feb 22 '18 at 19:13
  • Why are you using ${!i} in the function? What are you trying to do? – Kusalananda Feb 22 '18 at 19:15
  • 1
    Are you sure you don't have ${bar} mistyped as {$bar} when you use the function? Because that would add the braces. – ilkkachu Feb 22 '18 at 19:18
  • And yeah, using ${!i} there seems a bit weird. Something like for x in "$@" ; do echo "$x" ; done would seem more usual. Or "${@:1:5}" to just pick the first five arguments. – ilkkachu Feb 22 '18 at 19:22

To iterate over the arguments passed to a function (this also works for iterating over the arguments in scripts):


foo () {
    for i in "$@"; do
        printf 'Argument is "%s"\n' "$i"

foo a b "c d" e "f g h"


Argument is "a"
Argument is "b"
Argument is "c d"
Argument is "e"
Argument is "f g h"

Or, with your values:

foo string1 string2 ${foo} ${bar} ${s}

which generates

Argument is "string1"
Argument is "string2"
Argument is "/some/path/to/file.sh"
Argument is "username@myserver:/another/dir/"
Argument is "myserver"

It is likely that you have a typo in your code that swaps the $ and { in ${bar}:

$ foo {$bar}
Argument is "{username@myserver:/another/dir/}"
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.