简体   繁体   中英

How can I pass in arguments to a command line Java program and escape all special characters?

I have a command line Java program, and I am passing in the arguments via a bash script. The line is located in my bash script file and is as follows:

java -cp "$PROJECT_LOC" Main.main "@$"

The bash script is in my path so I can call the program directly by typing in

<projectName> arg1 arg2 arg3

directly into my terminal (I am on OS X Yosemite).

When an ampersand is passed in as an argument, it is not read as a plain ampersand character but as the special character ampersand which executes some process. However, I would like to be able to simply pass in an ampersand as an argument but not have to make the user of the program manually escape the character.

Is there a way to handle the passing in of an ampersand (or any other special characters) in my bash script such that any and all special characters in the input would be escaped, and then be passed in as the (now cleaned) args of the Java program?

Edit: To be more clear, I want to be able to do the following in my terminal:

<projectName> arg1 arg&2 arg3

I want this input to be equivalent to this:

<projectName> 'arg1' arg&2' 'arg3'

But I am looking for a way to not to have to force the user to escape the special characters themselves (do everything behind the scenes).

You can put single quotes (') around each argument. I'm not sure if that counts as "escaping" the arguments, though.

You need to quote/escape the ampersand on the command line. When you enter a command like:

<projectName> arg1 arg&2 arg3

The shell parses it into two separate commands, <projectName> arg1 arg and 2 arg3 , and decides that the first one should be backgrounded. Your script cannot see the 2 arg3 (that's a separate command) or even the & (that's a delimiter after the command). All of this gets decided before your script runs, and actually even before the shell gets around to figuring out that <projectName> corresponds to your script.

Your script has precisely zero control over any of this.

To put it another way: the command line will be parsed according to standard shell syntax, and standard shell syntax says that an unescaped/unquoted ampersand is a delimiter between commands. Your script cannot make itself an exception to this syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM