Reputation: 29131
I just wrote a program in c language which uses command line arguments and i tried to print the first argument. when i execute program with following command
./a.out $23
and try to print the first argument using the below code
printf("%s", argv[1]);
the output is just
3
Am i missing something here, that command line arguments are treated differently if some special characters are present. can some one explain this behavior.
Upvotes: 2
Views: 168
Reputation: 305
You have to "inhibit" you argument like this:
./a.out \$23
Some characters are interpreted by the shell. These characters include the following:
\
Which inhibits (escapes) the character just behind it (usefull for space, tabs or in your case)*
Which represents any single character or character strings$
Which represents a variable (in your case, the shell understands the variable $23, not the string "$23")||
or |
Which allows a resolution in your command or to pipe your command&&
or &
Which allows combination of commands or which allows the use of job control"
Which allows the shell to delimit a character string'
Which allows the shell to not interpret a character string with special characters;
Which delimits commands`
Which interprets the command enclosed by two of these and returns the command's outputUpvotes: 3
Reputation: 531808
The shell treats $23
as the positional parameter $2
followed by the literal character 3. To pass the string "$23", do either
./a.out \$23
or
./a.out '$23'
To pass the shell's 23rd positional parameter (unlikely, but possible), you would write
./a.out ${23}
Upvotes: 1
Reputation: 37928
Presumably the $2
is being treated as a shell variable. Try escaping the dollar sign:
./a.out \$23
Upvotes: 4