Page 1 of 1

[Solved] [Bash] How bash treats variables

Posted: 2023-11-28 02:39
by LinuxOS

Code: Select all

$ foo=bar
$ echo $foo
bar
$ foo=baz echo $foo
bar
$ foo=baz sh -c 'echo $foo'
baz
Hello!
Can anybody explain to me why foo=baz echo $foo results in bar, but then it works properly when I use sh -c?
Thanks!

Re: [Bash] How bash treats variables

Posted: 2023-11-28 03:15
by steve_v
This is an ancient question, and is answered multiple times elsewhere. It also smells suspiciously like homework...
Short version: variables are evaluated (i.e. env for the child process is constructed) before the command-line is executed, unless they are protected by single quotes. This applies also to builtins like echo.
LinuxOS wrote: 2023-11-28 02:39it works properly when I use sh -c?
There's nothing "improper" about the first result, it's expected (though arguably somewhat confusing) behaviour. You'll find shells other than bash do this as well.