命令行参数中的*问题 [英] The issue of * in Command line argument

查看:94
本文介绍了命令行参数中的*问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用Java编写了一个程序,该程序通过命令行参数接受输入。
我从命令行输入了两个数字和一个运算符。
要相乘两个数字,我必须输入例如 5 3 * ,但它不能按书面要求工作。



为什么不接受 * 从命令行?

解决方案

那是因为 * 是shell通配符:它对shell有特殊的含义,它将在传递给命令之前进行扩展(在本例中为 java )。 / p>

由于您需要文字 * ,因此需要从外壳中将其转义。转义的确切方法因外壳而异,但是您可以尝试:

  java ProgramName 5 3 * 

或:

  java ProgramName 5 3 \ * 






按的方式,如果您想了解shell对 * 的作用,请尝试打印 String [] args 转到您的 main 方法。您会发现它将包含目录中文件的名称。



如果您需要将一些文件名作为命令行参数传递,这将很方便。

>

另请参见




  • 维基百科:glob


    如果目录包含两个文件, a.log b.log ,则命令 cat * .log 将被shell扩展为 cat a.log b.log



  • 维基百科:转义字符


    在Bourne shell( sh )中,星号( * )和问号()字符是通配符,可以通过通配符扩展。如果没有前面的转义字符,则 * 将扩展为工作目录中所有不以句点开头的文件的名称,并且仅当存在此类文件时,否则 * 不会扩展。因此,要引用一个字面上称为 * 的文件,必须告知外壳程序不要以这种方式解释它,方法是在其前面加上反斜杠( \ )。




I wrote a program in Java that accepts input via command line arguments. I get an input of two numbers and an operator from the command line. To multiply two numbers, I have to give input as e.g. 5 3 *, but it's not working as written.

Why is it not accepting * from the command line?

解决方案

That's because * is a shell wildcard: it has a special meaning to the shell, which expands it before passing it on to the command (in this case, java).

Since you need a literal *, you need to escape it from the shell. The exact way of escaping varies depending on your shell, but you can try:

java ProgramName 5 3 "*"

Or:

java ProgramName 5 3 \*


By the way, if you want to know what the shell does with the *, try printing the content of String[] args to your main method. You'll find that it will contain names of the files in your directory.

This can be handy if you need to pass some filenames as command line arguments.

See also

  • Wikipedia: glob

    For example, if a directory contains two files, a.log and b.log then the command cat *.log will be expanded by the shell to cat a.log b.log

  • Wikipedia: Escape character

    In Bourne shell (sh), the asterisk (*) and question mark (?) characters are wildcard characters expanded via globbing. Without a preceding escape character, an * will expand to the names of all files in the working directory that don't start with a period if and only if there are such files, otherwise * remains unexpanded. So to refer to a file literally called "*", the shell must be told not to interpret it in this way, by preceding it with a backslash (\).

这篇关于命令行参数中的*问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆