KishoreReddy KishoreReddy - 8 months ago 44
Bash Question

How to prevent substitution of $1 value, while passing the argument value as 'abc$1xyz' in shell script


echo $1;
foo $1

running the script as: ./ abc$1xyz

Output is:


But expecting output is:


So, here $1 value is replacing with empty, but I want to prevent that. I know we can do with using single quotes like foo 'abc$1xyz' but actually I can't do that, because that value will passing from third person, I can't tell them to add single quotes or any escaping characters. So, please let me know is there any other work around will be available for this.

Edit: Based on the requested comments, and please tell me still you need any clarity the one who had down voted this.

Answer Source

In short, you can't do what you want. If someone is using your tool from the command line, they simply must use your command according to the rules of the shell.

The behavior you are seeing is because the shell will translate the argument before your program ever sees it. There is absolutely no way for your command to affect what happens before it is called.

It is because of this -- because the shell processes arguments before running your script -- that quotes were created in the first place. Quoting (both single quotes, double quotes, and backslash quotes) exists to give users control over how arguments are treated before calling some function.

So, if you want a string like abc$1xyz to be sent to your program without variable expansion you have two choices:

  • require the user to use some other shell that doesn't translate arguments before calling your program, or
  • require the user to use the facilities of the shell to properly quote their arguments.