Strange behavior of argv when passing string containing “!!!!”

前端 未结 3 922
[愿得一人]
[愿得一人] 2020-12-30 20:40

I have written a small program that takes some input parameters from *argv[] and prints them. In almost all use cases my code works perfectly fine. A problem on

3条回答
  •  傲寒
    傲寒 (楼主)
    2020-12-30 20:50

    This is not related to your code but to the shell that starts it.

    In most shells, !! is shorthand for the last command that was run. When you use double quotes, the shell allows for history expansion (along with variable substitution, etc.) within the string, so when you put !! inside of a double-quoted string it substitutes the last command run.

    What this means for your program is that all this happens before your program is executed, so there's not much the program can do except check if the string that is passed in is valid.

    In contrast, when you use single quotes the shell does not do any substitutions and the string is passed to the program unmodified.

    So you need to use single quotes to pass this string. Your users would need to know this if they don't want any substitution to happen. The alternative is to create a wrapper shell script that prompts the user for the string to pass in, then the script would subsequently call your program with the proper arguments.

提交回复
热议问题