如何将 bash 中的星号字符“*”作为参数传递给我的 C 程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2755795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:15:13  来源:igfitidea点击:

How do I pass in the asterisk character '*' in bash as arguments to my C program?

bashescaping

提问by Yz Chong

Let's say I have a C program, and I run it from bash:

假设我有一个 C 程序,我从 bash 运行它:

$ ./a.out 123 *

The program would output all the command line arguments, but it will show these instead:

该程序将输出所有命令行参数,但它会显示这些:

Argument 1: 123
Argument 2: a.out

What can I do in my program to fix this?

我可以在我的程序中做些什么来解决这个问题?

回答by James McNellis

The shell is replacing the asterisk with the name of each file in the directory.

shell 正在用目录中每个文件的名称替换星号。

To pass a literal asterisk, you should be able to escape it:

要传递文字星号,您应该能够将其转义:

$ ./a.out 123 \*

回答by frankc

Another option is to use set -fto turn off expansion. Compare:

另一种选择是用于set -f关闭扩展。相比:

echo *

v.s.

对比

set -f
echo *

You can turn it back on with set +f:

您可以使用set +f以下命令重新打开它:

set -f
echo *
set +f
echo *

回答by Matthew Flaschen

You can quote it in the shell

你可以在shell中引用它

./a.out 123 '*'

There is nothing you can do in your program, because the * expansion is done by the shell (in contrast to Windows, where it's done by the program).

在你的程序中你什么也做不了,因为 * 扩展是由 shell 完成的(与 Windows 不同,它由程序完成)。

回答by Mahn

Another alternative is to start your script with #!/bin/bash -fas the first line, which will allow you to accept literal strings as arguments (including the asterisk), and thus that will allow you to run ./a.out 123 *with the desired input, but note that bash -fdisables expansions completely, and that can have adverse effects in your script depending on what you do.

另一种选择是将脚本#!/bin/bash -f作为第一行开始,这将允许您接受文字字符串作为参数(包括星号),从而允许您./a.out 123 *使用所需的输入运行,但请注意bash -f完全禁用扩展,并且这可能会对您的脚本产生不利影响,具体取决于您的操作。

回答by J?rg W Mittag

This doesn't have anything to do with your program.

这与您的程序没有任何关系。

The *is a wildcard in Bash, it means "all files in the current directory". If you want to pass an asterisk as an argument to your program, you do it the same way you do it with every other program: you escape it with a backslash or quote it.

*是Bash的一个通配符,它的意思是“在当前目录下的所有文件”。如果您想将星号作为参数传递给您的程序,您可以按照与其他所有程序相同的方式执行此操作:用反斜杠将其转义或引用它。