Set environment variable inside shell alias

I have two versions of Java installed on my system - some programs require Java 7, some require Java 8.

Java 8 is my default system, so when I executed the Java 7 commands, I used:

JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.*.jdk/Contents/Home/ \
java_7_program

I want to set an alias to write instead

j7 java_7_program

I defined:

alias j7='JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.*.jdk/Contents/Home/'

But then the launch j7 java -versioncalls:

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 why this does not work?

bash --version prints GNU bash, version 4.3.42(1)-release (x86_64-apple-darwin14.5.0)

A more isolated example (minus java):

$ alias foo='BAR=baz'
$ type foo
foo is aliased to `BAR=baz'
$ foo echo $BAR
[blank line]
+4
source share
3 answers

:

- :

bar=foo my_command

bar my_command ( ). , :

bar=stuff
bar=foo my_command "$bar"

$bar my_command, :

bar=foo my_command stuff

$bar , my_command . [blank line], :

$ alias foo='BAR=baz'
$ type foo
foo is aliased to `BAR=baz'
$ foo echo $BAR
[blank line]

:

$ alias foo=BAR=baz
$ BAR=something
$ foo echo "$BAR"
something

?

$ alias foo=BAR=baz
$ foo eval 'echo "$BAR"'
baz

, bar eval, echo "$BAR" ... ( !).

,

$ alias foo=BAR=baz
$ foo sh -c 'echo "$BAR"'
baz
+4

, jdk1.7.*.jdk. ,

/usr/libexec/java_home -v 1.7, 1.7.

, , :

alias j7='JAVA_HOME=`/usr/libexec/java_home -v 1.7`'

java_home, , JAVA_HOME.

+1

- .

,

script .

sudo cat >/usr/local/bin/j7 <<<eof
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.*.jdk/Contents/Home/
java $@
eof
sudo chmod +x /usr/local/bin/j7

.bashrc:

j7() {
  export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.*.jdk/Contents/Home/
  java $@
}

bash

- :

j7 () {
    local JLIBROOT dir
    # JLIBROOT=/usr/lib/jdk
    JLIBROOT=/Library/Java/JavaVirtualMachines
    while read dir && [ "$dir" = "${dir//1.7.}" ] ;do
        :
      done < <(
          /bin/ls -1trd $JLIBROOT/*
    )
    if [ "$dir" != "${dir//1.7.}" ] ;then
          export JAVA_HOME=$dir/Contents/Home
          java $@
      else
          echo "Version 1.7 not found in '$JLIBROOT'."
      fi
}

Linux...

+1

Source: https://habr.com/ru/post/1613315/


All Articles