17

I have a Java program which I'm executing in a Linux environment through a bash script.

This is my simple bash script, which accepts a String.

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

The issue is that the command line argument can be with Spaces or Without spaces.

For example it can be either:

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 issue is that , when I am trying to execute it this way:

./quotetester Apple Inc. 2013 Jul 05 395.00 Call

its only always going to the else condition that is Stock .

Is there anyway I can resolve this?

Salix alba
  • 7,536
  • 2
  • 32
  • 38

5 Answers5

26

When you pass command line arguments with spaces, they are taken as space separated arguments, and are splitted on space. So, you don't actually have a single argument, but multiple arguments.

If you want to pass arguments with spaces, use quotes:

java classname "Apple Inc. 2013 Jul 05 395.00 Call"
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
12

This is not a Java issue per se. It's a shell issue, and applies to anything you invoke with such arguments. Your shell is splitting up the arguments and feeding them separately to the Java process.

You have to quote the arguments such that the shell doesn't split them up. e.g.

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

etc. See here for a longer discussion.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

The arguments are handled by the shell , so any terminal settings should not affect this. You just need to have quoted argument and it should work.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0

Single quotes are the best option

Spaces and double quotes can be resolved this way.

java QuerySystem '((group = "infra") & (last-modified > "2 years ago"))' 
Ammad
  • 4,031
  • 12
  • 39
  • 62
0

In the original question the OP is using a shell script to call a java command line and would like the shell script to pass the arguments without performing the Blank interpretation (Word Splitting) option of input interpretation https://rg1-teaching.mpi-inf.mpg.de/unixffb-ss98/quoting-guide.html#para:sh-ifs

If you know how many arguments there are then you can double quote the arguments

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

So you call this script, save as quotetester.sh.

./quotetester.sh "hello world" 

and "hello world" gets passed as a single argument to Java. You could also use

./quotetester.sh hello\ world 

with the same effect.

Salix alba
  • 7,536
  • 2
  • 32
  • 38