Strange behavior of argv when passing string containing "!!!!" Strange behavior of argv when passing string containing "!!!!" bash bash

Strange behavior of argv when passing string containing "!!!!"


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.


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.


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.