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

馋奶兔 提交于 2019-12-17 04:05:34

问题


Let's say I have a C program, and I run it from 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?


回答1:


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

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

$ ./a.out 123 \*



回答2:


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

echo *

v.s.

set -f
echo *

You can turn it back on with set +f:

set -f
echo *
set +f
echo *



回答3:


You can quote it in the 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).




回答4:


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.




回答5:


Another alternative is to start your script with #!/bin/bash -f as 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 -f disables expansions completely, and that can have adverse effects in your script depending on what you do.



来源:https://stackoverflow.com/questions/2755795/how-do-i-pass-in-the-asterisk-character-in-bash-as-arguments-to-my-c-program

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!