How can I supply arguments from variable value to the command in shell script?
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.javaHowever, 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.javaWhich is perfectly right.
Why is this happening? Is it that I can't supply arguments to a command from variable value?
11 Answer
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
foo
bar baz 3