I am trying to make a shell script in which I want to pass the -classpath "classpath-value" flag to the javac command. I know I can use the CLASSPATH environment variable to set the classpath, but I have a very specific need to do it this way.

What I want:

$ classpath_val="-classpath \"/opt/apache-tomcat-8.5.20/lib/servlet-api.jar\""
$ javac $classpath_val com/example/Test.java

However, when I executed the second command, it just executes as if the classpath_val were not supplied, so it doesn't use the -classpath flag.

But if I echo the same command, I get:

$ echo javac $classpath_val com/example/Test.java
javac -classpath "/opt/apache-tomcat-8.5.20/lib/servlet-api.jar" com/example/Test.java

Which is perfectly right.

Why is this happening? Is it that I can't supply arguments to a command from variable value?

  • @steeldriver Thank you for giving the solution. It works perfectly. Dec 31, 2017 at 15:27

1 Answer 1


In bash, probably the most robust way to do this is using an array e.g.

classpath_val=("-classpath" "/opt/apache-tomcat-8.5.20/lib/servlet-api.jar")

then expand each element in a whitespace-safe way using

javac "${classpath_val[@]}" com/example/Test.java 

Quoting the elements in both the array construction and expansion prevents them from being split on whitespace. To illustrate:

$ arr=("foo" "bar baz")
$ set -- "${arr[@]}"
$ for f; do echo "$f"; done
bar baz
  • Is it possible to put the classpath value in double quotes. Because a space anywhere in classpath value will break it. Dec 31, 2017 at 15:37
  • @KashyapKansara spaces should not break it if you use quotes as I have shown - do you have a specific example where that's not the case? Dec 31, 2017 at 15:50
  • @steeldriver Hey...sorry...sorry...It is working perfectly fine with spaces. I have just checked it. Thank you for taking time to answer my question. Dec 31, 2017 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.