Passing arguments with spaces from a bash script to another script.

Hi Guys,

Very quick “Today I Learned” snippet. If you want to pass arguments, that have spaces, in a bash script to another script (in my case I wanted to pass the arguments passed from a bash script to a java class) do the following in the bash file:

#Content from the java_task.sh

java MyClass “$@”

This will pass all arguments the bash script received to the Java class. So if you invoke the script as:

./java_task.sh argument1 “argument two”

Then in your Java program you can do:

public static void main(String[] args) {

     String arg1 = args[0] // “argument1”

    String arg2 = args[1] // “argument two”

}

Do remember that the argument with spaces must be enclosed in quotes.

Happy coding.

Leave a Reply

Your email address will not be published. Required fields are marked *