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

前端 未结 3 921
[愿得一人]
[愿得一人] 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.

    0 讨论(0)
  • 2020-12-30 20:53

    In addition to the supplied answers, you should remember that echo is your shell friend. If you prefix your command with "echo ", you will see what shell is actually sending to your script.

    echo ./program -m "Hello, world!!!!"
    

    This would have showed you some strangeness and might have helped steer you in the right direction.

    0 讨论(0)
  • 2020-12-30 21:12

    The shell does expansion in double-quoted strings. And if you read the Bash manual page (assuming you use Bash, which is the default on most Linux distributions) then if you look at the History Expansion section you will see that !! means

    Refer to the previous command.

    So !!!! in your double-quoted string will expand to the previous command, twice.

    Such expansion is not made for single-quoted strings.

    So the problem is not within your program, it's due to the environment (the shell) calling your program.

    0 讨论(0)
提交回复
热议问题