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

前提是你 提交于 2021-02-07 04:41:12

问题


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.


回答1:


# 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



回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/58837835/unable-to-pass-character-as-a-command-line-argument

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