Star Hype News.

Premium celebrity moments with standout appeal.

updates

How can I supply arguments from variable value to the command in shell script?

By John Thompson

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?

1

1 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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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