- Published on
Shell Variable Expansion
In POSIX shells (bash, sh, zsh), variable expansion happens before command execution, so variables assigned earlier on the same line are not available for expansion later on that line.
Why this fails
ARTIFACTORY_USER="alice" echo "${ARTIFACTORY_USER}"
What actually happens:
- Shell performs parameter expansion →
${ARTIFACTORY_USER}(old value or empty) - Shell executes the command with a temporary environment assignment
So the expansion does not see the new value.
Correct ways to do it
✅ Use && (what you suggested)
ARTIFACTORY_USER="alice" && echo "${ARTIFACTORY_USER}"
This works because:
- The assignment runs first
- The variable is set in the shell
- The next command sees it
✅ Use separate lines (most readable)
ARTIFACTORY_USER="alice"
echo "${ARTIFACTORY_USER}"
✅ Use a subshell if you want scoping
(
ARTIFACTORY_USER="alice"
echo "${ARTIFACTORY_USER}"
)
Important distinction
This does work, but only for the executed command—not for expansion:
ARTIFACTORY_USER="alice" env | grep ARTIFACTORY_USER
Because env reads the environment at execution time, not expansion time.
Rule of thumb
Never rely on variable expansion from assignments made on the same command line. Use
&&, newlines, or a subshell instead.