Yz Chong
Yz Chong

Reputation: 391

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

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?

Upvotes: 39

Views: 48531

Answers (5)

frankc
frankc

Reputation: 11483

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 *

Upvotes: 31

Mahn
Mahn

Reputation: 16603

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.

Upvotes: 5

Jörg W Mittag
Jörg W Mittag

Reputation: 369594

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.

Upvotes: 5

James McNellis
James McNellis

Reputation: 355307

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 \*

Upvotes: 45

Matthew Flaschen
Matthew Flaschen

Reputation: 285037

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).

Upvotes: 22

Related Questions