I'm trying to use an environment variable in a command, but when I run `foo=bar echo "$foo"`, it just prints a blank line instead of "bar". Can anyone explain what's going wrong here?
2 Answers
If you're looking to print 'bar' directly, try using `foo="bar"; echo "$bar"`. Just remember that you'll need to separate the commands with a semicolon so that the variable is set before you reference it.
Yes, it will! If you want it only for one command, you could do something like `AWS_ACCESS_KEY=ABCDEFG AWS_SECRET_ACCESS_KEY=NOPQRST aws ecr get-login-password...`. This way, the variable is scoped just for that command.
The reason you're getting a blank line is that `$foo` is evaluated by the shell before the command gets executed, and at that point, the variable hasn't been set yet. So, `echo` doesn't see any value to print.
Got it! But won't that set `foo` for future commands too?