Reputation: 437
I have a java project that I launch using a bash file :
#!/usr/bin/env bash
java -classpath logger/bin:banking/bin:testframework/bin test.RunTest
I launch my bash in my terminal (in ubuntu) :
firefrost@firefrost-PC:~/ProjetPOO3A$ bash test.sh banking.Account
In my main, I try to get arguments as :
public class RunTest {
public static void main(String[] args) {
System.out.println(args.length);
for(int i = 0; i < args.length; i++)
{
...
The problem is that args.length is 0 when it should be 1 because I passed the argument "banking.Account" in my console.
If I put the argument in the bash file :
#!/usr/bin/env bash
java -classpath logger/bin:banking/bin:testframework/bin test.RunTest banking.Account
my main recognize the argument and the System.out.println outputs 1.
Why is the argument in the console not taken into account?
Upvotes: 1
Views: 1914
Reputation: 3097
Add "$@"
to pass the arguments to the program:
#!/bin/bash
java -classpath logger/bin:banking/bin:testframework/bin test.RunTest "$@"
Don't forget the quotes around $@
so bash will "protect" each argument:
@
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).
See bash man.
Upvotes: 1
Reputation: 362
You forget to process the argument in the bash file.
You can access them by using $1, $2, $3, $... variables.
For example writing ./my.sh test test2
$1 will contain test and $2 test2
So change your script to
#!/usr/bin/env bash
java -classpath logger/bin:banking/bin:testframework/bin test.RunTest $1
Upvotes: 1
Reputation: 4919
There is no problem in Java code. Your parameters are not propagated to java
command in shell script.
#!/usr/bin/env bash
java -classpath logger/bin:banking/bin:testframework/bin test.RunTest "$@"
The $@
variable contains all parameters passed to shell script.
Upvotes: 2
Reputation: 8446
Command line arguments to a bash script can be accessed with $1
, $2
, etc. Here's a fuller explanation.
Try updating your script as follows:
#!/usr/bin/env bash
java -classpath logger/bin:banking/bin:testframework/bin test.RunTest $1
Upvotes: 1