简体   繁体   中英

Bash adds an extra character to java call

I have a java program I call from the command line like so:

java -cp bin Main a b 2

The last argument is important because it is a number and I use Integer.parseInt to read it. When I use a bash script, I use:

java -cp bin Main $1 $2 $3

And I call the script with:

./script a b 2

However, when I call the script it cannot parse the 2 because there is a extra character added to the last argument. I tried to print the second character, but it doesn't print a readable character. I assume the extra character is a \\n or \\r or some such character. When I have "2" as the second argument instead of the third, this doesn't happen. Could anyone help me understand what is going on? Do I just ignore the last character? Thanks.

Bash didn't add anything. Your editor did. Always make sure you save your file as a UNIX format text file to avoid carriage returns.

Just for practice, let's make a simple, self contained test case to make it easier for ourselves and others to figure out your problem. Tips for doing this is described on the bash tag wiki .

Here's a simple program to call to verify the behavior:

$ cat javamock
#!/bin/bash
echo "The third argument has ${#3} characters"

$ ./javamock a b 2
The third argument has 1 characters

Here's what you're seeing

$ cat yourscript 
./javamock $1 $2 $3

$ bash yourscript a b 2
The third argument has 2 characters

Ok, so how do we diagnose it? Here's how we can tell something's up with your script:

$ shellcheck yourscript
In yourscript line 1:
./javamock $1 $2 $3
                   ^-- SC1017: Literal carriage return. Run script through tr -d '\r' .

or how to confirm if you already know what you're looking for:

$ cat -v yourscript
./javamock $1 $2 $3^M

And finally, the applied fix:

$ tr -d '\r' <yourscript  >fixedscript
$ bash fixedscript a b 2
The third argument has 1 characters

It's wise to sanitize inputs trimming trailing and leading whitespace (not just for command line arguments, but most of the time when you are reading text data).

If you want to know what character it is, try printing its numeric value (cast to a short ).

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