0

I have a bazinga property stored in an environment variable

export OPTS="-Dbazinga=\"foo bar\""
-bash-4.1$ echo $OPTS
-Dbazinga="foo bar"

Also, there is an example java program that just prints its value:

public class Main {
    public static void main(String[] args) {
        System.out.println(System.getProperty("bazinga", ""));
    }
}

When I run the program without using the env variable everything works fine, meaning foo bar is printed:

-bash-4.1$ java -Dbazinga="foo bar" Main
foo bar

However, I am unable to run the program using the variable because qoutation marks get in the way:

-bash-4.1$ java $OPTS Main
Error: Could not find or load main class bar"

-bash-4.1$ java "$OPTS" Main
"foo bar"

How can I run the program using the env variable with correct quotation marks handling?

  • I’m not sure backslashes work in Unix shells the same way they work in Java code. Try defining the environment variable this way: `export OPTS="-Dbazinga='foo bar'"` – VGR Nov 17 '21 at 12:40
  • Now it prints `'foo bar'` – jan.n.nowak Nov 17 '21 at 12:42
  • Even when you run it using `java $OPTS Main` without any quotes in the command line? – VGR Nov 17 '21 at 12:42
  • When I run `java $OPTS Main` then I get `Error: Could not find or load main class bar'` – jan.n.nowak Nov 17 '21 at 12:46
  • I suppose that makes sense; the quotes in an expanded value are just text, not shell metacharacters. You can do `bash -c "java $OPTS Main"`, though I’m not particularly fond of that since it can introduce other problems, should your case become more complex. – VGR Nov 17 '21 at 12:51
  • See [Why does shell ignore quoting characters in arguments passed to it through variables?](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quoting-characters-in-arguments-passed-to-it-through-varia) (and many similar questions). – Gordon Davisson Nov 17 '21 at 18:15

0 Answers0