views:

54

answers:

3

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.
+1  A: 

you forgot the semicolon

alias hi='TEST=ok ;echo $TEST'

ghostdog74
+2  A: 

The problem has nothing to do with aliases. Simply running

$ TEST=ok echo $TEST

$

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:

  1. $TEST is expanded
  2. TEST is assigned 'ok'
  3. echo is 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 $TEST in the second command because it has already been set.

camh
A: 

For completeness:

$ echo 'echo $TEST'>echotest
$ unset $TEST
$ TEST=ok . ./echotest
ok
$ chmod u+x echotest
$ TEST=ok ./echotest
ok
$ echo $TEST
$

In this case, setting TEST=ok modifies the environment of the script echotest which does not expand the $TEST inside it until it's run.

Dennis Williamson
Thanks guys! I'd tried it from the command line and thought it had worked w/o the ';' but I suppose that was a mistake where I hadn't unset the variable first!
jay