Problem with command line arguments that got spaces in it

I have a Java program that I run in a Linux environment through a bash script.

This is my simple bash script that takes a string.

#!/bin/bash java -cp com.QuoteTester $1 

The problem is that the command line argument can be with spaces or without spaces.

For example, it could be:

 Apple Inc. 2013 Jul 05 395.00 Call 

OR

 Apple 

My code is:

 public static void main(String[] args) { String symbol = args[0]; if (symbol.trim().contains(" ")) // Option { } else // Stock { } } 

So the problem is that when I try to execute it as follows:

 ./quotetester Apple Inc. 2013 Jul 05 395.00 Call 

its only thing always happens in an else condition which is a margin.

Can I solve this problem?

+8
source share
4 answers

When you pass command line arguments with spaces, they are treated as space-separated arguments and separated by spaces. Thus, you actually have no arguments, but several arguments.

If you want to pass arguments with spaces, use quotation marks:

 java classname "Apple Inc. 2013 Jul 05 395.00 Call" 
+18
source

This is not a Java issue as such. This is a shell problem and applies to everything that you invoke with such arguments. Your shell separates the arguments and passes them separately to the Java process.

You must quote the arguments so that the shell does not break them. eg.

 $ java -cp ... "Apple Inc. 2013" 

etc .. See here for a longer discussion .

+7
source

Arguments are processed by the shell, so any terminal settings should not affect this. You just need to specify an argument and it should work.

+1
source

Single quotes are the best option.

Spaces and double quotes can be resolved this way.

 java QuerySystem '((group = "infra") & (last-modified > "2 years ago"))' 
0
source

Source: https://habr.com/ru/post/1491153/


All Articles