Scheduled Maintenance: We are aware of an issue with Google, AOL, and Yahoo services as email providers which are blocking new registrations. We are trying to fix the issue and we have several internal and external support tickets in process to resolve the issue. Please see: viewtopic.php?t=158230

 

 

 

[Solved] [Bash] How bash treats variables

Programming languages, Coding, Executables, Package Creation, and Scripting.
Post Reply
Message
Author
User avatar
LinuxOS
Posts: 52
Joined: 2022-07-31 01:46
Has thanked: 27 times
Been thanked: 3 times

[Solved] [Bash] How bash treats variables

#1 Post 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!
Last edited by LinuxOS on 2023-11-28 09:51, edited 1 time in total.

steve_v
df -h | grep > 20TiB
df -h | grep > 20TiB
Posts: 1418
Joined: 2012-10-06 05:31
Location: /dev/chair
Has thanked: 80 times
Been thanked: 191 times

Re: [Bash] How bash treats variables

#2 Post 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.
Once is happenstance. Twice is coincidence. Three times is enemy action. Four times is Official GNOME Policy.

Post Reply