cd-00
cd-00

Reputation: 605

Unable to pass '#' character as a command-line argument

I can't pass strings starting with # as command-line arguments.

Here is a simple test:

#include <stdio.h>

int main(int argc, char *argv[])
{
    for (int i = 1; i < argc; i++)
        printf("%s ", argv[i]);

    putchar('\n');

    return 0;
}

If I input the arguments as follows:

2 4 # 5 6

The value of argc is 3 and not 6. It reads # and stops there. I don't know why, and I can't find the answer in my copies of The C Programming Language and C Primer Plus.

Upvotes: 36

Views: 3126

Answers (3)

S.S. Anne
S.S. Anne

Reputation: 15566

It's because you're using an sh-like shell. Quote the # or escape it using \ and it will work.

This is called a comment in sh. It causes the # (space-hash) and any arguments after it to be discarded. It's used similarly to comments in C, where it is used to document code.

Strings beginning with $ are called variables in sh. If you haven't set a variable, it will expand to an empty string.

For example, all of these would be valid ways to pass the # to your application:

2 4 '#' 5 6
2 4 "#" 5 6
2 4 \# 5 6

And these would be valid ways to pass a string starting with $:

2 4 '$var' 5 6
2 4 '$'var 5 6
2 4 \$var 5 6

Please note that variables inside "s are still expanded.

Upvotes: 8

fanduin
fanduin

Reputation: 1189

# begins a comment in Unix shells, much like // in C.

This means that when the shell passes the arguments to the progam, it ignores everything following the #. Escaping it with a backslash or quotes will mean it is treated like the other parameters and the program should work as expected.

2 4 \# 5 6

or

2 4 '#' 5 6

or

2 4 "#" 5 6

Note that the # is a comment character only at the start of a word, so this should also work:

2 4#5 6

Upvotes: 47

VJAYSLN
VJAYSLN

Reputation: 473

When passing the value through command line arguments you have to walk through these following instructions. The following characters have special meaning to the shell itself in some contexts and may need to be escaped in arguments:

` Backtick (U+0060 Grave Accent)
~ Tilde (U+007E)
! Exclamation mark (U+0021)
# Hash (U+0023 Number Sign)
$ Dollar sign (U+0024)
& Ampersand (U+0026)
* Asterisk (U+002A)
( Left Parenthesis (U+0028)
) Right parenthesis (U+0029)
 (⇥) Tab (U+0009)
{ Left brace (U+007B Left Curly Bracket)
[ Left square bracket (U+005B)
| Vertical bar (U+007C Vertical Line)
\ Backslash (U+005C Reverse Solidus)
; Semicolon (U+003B)
' Single quote / Apostrophe (U+0027)
" Double quote (U+0022)
↩ New line (U+000A)
< Less than (U+003C)
> Greater than (U+003E)
? Question mark (U+003F)
  Space (U+0020)1

Upvotes: 12

Related Questions