As I understand and read it, $@
turns into "arg1" "arg2" "arg3".
But it seems to have some weird behavior in some cases when quoted.
Test 1, $@
$ function somefunc { sh -c "echo $@"; }
$ somefunc 1 2 3
> + somefunc 1 2 3
> + sh -c 'echo 1' 2 3
> 1
The expected output is 1 2 3, the output I get is 1. Now I see that, for some reason, it seems to only pass echo 1
as command, but why does "echo "1" "2" "3""
turn into it? I would maybe have expected echo
because the " before echo may get closed by the " before 1.
Test 2, $*
$ function somefunc { sh -c "echo $*"; }
$ somefunc 1 2 3
> + somefunc 1 2 3
> + sh -c 'echo 1 2 3'
> 1 2 3
This is pretty obvious and works, just to make sure. After all $*
passes 1 2 3
, not "1" "2" "3"
.
Test 3, $@ and $*
$ function somefunc { sh -c "echo $@ $*"; }
$ somefunc 1 2 3
> + somefunc 1 2 3
> + sh -c 'echo 1 2 3 1 2 3'
> 1 2 3 1 2 3
This seems to work again weirdly enough. But I don't get how "echo "1" "2" "3" 1 2 3"
turns into 'echo 1 2 3 1 2 3'
and doesn't follow the "pattern" that only "echo $@"
did.
Test 4, $@ and a string
$ function somefunc { sh -c "echo $@ hi"; }
$ somefunc 1 2 3
> + somefunc 1 2 3
> + sh -c 'echo 1' 2 '3 hi'
> 1
This again follows the pattern of "echo $@"
, even thought, as I see it, it is pretty much the same as "echo $@ $*"
since $*
turns into a string after all.
What also puzzles me is that it turned into 'echo 1' 2 '3 hi'
, the first test would have suggested 'echo 1' 2 3 hi
(without the two '
surrounding 3 hi
)
Test 5, $@ and $var
$ var="hi"
> + var=hi
$ function somefunc { sh -c "echo $@ $var"; }
$ somefunc 1 2 3
> + somefunc 1 2 3
> + sh -c 'echo 1 2 3 hi'
> 1 2 3 hi
This works again. So $@
seems to work if another variable follows it.
The tests are also possible with su user -c
or bash -c
instead of sh -c
, so I suppose also every other command that executes the next given argument.
I now seem to have gotten some kind of behavior out of it,
but I do still not understand this behavior.
What am I missing here?