Linux – How to escape double quotes and exclamation mark in password

bashlinuxshshellshell-scripting

I have the following code:

curl -s --insecure -H "Content-Type: application/json" -X POST -d "{\"username\":\"$1\",\"password\":\"$2\"}" http://apiurl

In the above curl command I want to escape the " and ! in the password.

I have modified the curl command as below but it doesn't seem to work

curl -s --insecure -H "Content-Type: application/json" -X POST -d "{\"username\":\"$1\",\"password\":\"$2\"}" http://apiurl

Best Answer

${password//!/\!} will substitute every ! in the password with ! The extra \ signifies that we are looking to replace every ! and not just the first one.

The same logic can be used for " Alternatively, you may be able to enclose the complete -d variable in single quotes instead of double quotes and this may negate the need for escaping the double quotes.