Master
Master

Reputation: 103

How can I escape arguments passed in bash script command line

I have one variable, which is coming from some where like:

VAR1='hhgfhfghhgf"";2Ddgfsaj!!!$#^$\'&%*%~*)_)(_{}||\\/'

Now i have command like this

./myscript.sh '$VAR1'

I am getting that $VAR1 from some diff process and when I display it look exactly as its above.

Now that command is failing as there is already single quote inside variable. In the process where I use it it is expanded at that point, which causes that error.

I have control over myscript.sh but not above command.

Is there any way I can get variable inside my script?

Upvotes: 4

Views: 7916

Answers (1)

αғsнιη
αғsнιη

Reputation: 2771

What you are saying is not possible to failing when passing to your script. Might your script has processing issue (or a command where this argument will passing into it) which cannot expand the variable correctly. You can either use printf with %q modifier to escape all special characters then pass it to your script:

./myscript.sh "$(printf '%q\n' "$VAR1")"

... or do the same within your script before you wanted to pass to some other commands:

VAR2="$(printf '%q\n' "$VAR1")"

Upvotes: 5

Related Questions