简体   繁体   English

Bash向Java调用添加了额外的字符

[英]Bash adds an extra character to java call

I have a java program I call from the command line like so: 我有一个从命令行调用的Java程序,如下所示:

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. 最后一个参数很重要,因为它是一个数字,我使用Integer.parseInt来读取它。 When I use a bash script, I use: 当我使用bash脚本时,我使用:

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. 但是,当我调用脚本时,它无法解析2,因为在最后一个参数中添加了一个额外的字符。 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. 我假设多余的字符是\\ n或\\ r或类似的字符。 When I have "2" as the second argument instead of the third, this doesn't happen. 当我将“ 2”作为第二个参数而不是第三个参数时,这不会发生。 Could anyone help me understand what is going on? 谁能帮助我了解发生了什么事? Do I just ignore the last character? 我是否忽略了最后一个字符? Thanks. 谢谢。

Bash didn't add anything. Bash没有添加任何东西。 Your editor did. 您的编辑做了。 Always make sure you save your file as a UNIX format text file to avoid carriage returns. 始终确保将文件另存为UNIX格式的文本文件,以避免回车。

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 . bash标签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 ). 如果您想知道它是什么字符,请尝试打印其数字值( short )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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