I want to set an alias like so:
alias hi='TEST=ok echo $TEST'
However, it doesn’t seem to work reliably.
I start with:
unalias hi
unset TEST
Then:
$ alias hi="TEST=ok echo $TEST"
$ hi
$
This is on MacOSX:
$ bash --version
GNU bash, version 3.2.17(1)-release (i386-apple-darwin9.0)
Copyright (C) 2005 Free Software Foundation, Inc.
The problem has nothing to do with aliases. Simply running
does not echo anything (except a newline), since $TEST is expanded by the shell before the echo command is run.
Three things are happening in that statement in this order:
$TESTis expandedTESTis assigned ‘ok’echois executed (with TEST=ok in its environment)Placing a semicolon between the assignment and the echo command as suggested by ghostdog74 (
TEST=ok ; echo $TEST) causes the assignment to be a separate shell command executed before the echo command. The shell can then expand$TESTin the second command because it has already been set.