On my system, I've got two versions of Java installed - some programs require Java 7, some require Java 8.
Java 8 is my system default, so when I've been running the Java 7 commands, I've been using:
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.*.jdk/Contents/Home/ \
java_7_program
I want to set an alias so I can instead write
j7 java_7_program
I've defined:
alias j7='JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.*.jdk/Contents/Home/'
But then running j7 java -version
produces:
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
The man page (search for "Aliases") states that this is done as a direct substitution. Is there a reason as to why this isn't working?
bash --version
prints GNU bash, version 4.3.42(1)-release (x86_64-apple-darwin14.5.0)
A more isolated example (minus the java):
$ alias foo='BAR=baz'
$ type foo
foo is aliased to `BAR=baz'
$ foo echo $BAR
[blank line]
foo env
and you will see that BAR is set to baz. Also tryfoo /bin/echo $BAR
and that should work. The difference is that echo is a shell builtin, so explicitly running the binary does the right thing. – Richard Oct 27 '15 at 9:12foo echo $BAR
, thenBAR
isn't set in the current shell, only inecho
's environment; and$BAR
is expanded beforeecho
is run. Try any of these and you'll see it works: 1. typefoo
on its own line, andecho $BAR
afterwards or, equivalentlyfoo; echo "$BAR"
; 2.foo eval 'echo "$BAR"'
; 3. (somehow similar)foo bash -c 'echo "$BAR"'
. – gniourf_gniourf Oct 27 '15 at 9:13java
was using/bin/java
, which was using 1.8 irrespective of theJAVA_HOME
variable. – Fabian Tamp Oct 27 '15 at 9:25'
! Just whipe quotes:alias j7=JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.*.jdk/Contents/Home/
could work fine! – F. Hauri Oct 27 '15 at 9:34j7 ; j7 echo $JAVA_HOME
) then it works. – Fabian Tamp Oct 27 '15 at 9:43