Bash script - how to add slashes to quotations for sending to MySQL?
Hi all,
I have the following script: Code:
thedate=$(date +"%Y-%m-%d") The problem is that the string may contain " and ' characters which MySQL doesn't like. In PHP I would solve this problem by: $page_text= addslashes($page_text); but I have no idea how to do this in Bash. I can't even work out how to find/replace! Any help greatly appreciated. Leon |
The best place to look for these answers is in Advanced Bash Scripting Guide
Find and replace is Code:
${string/substring/replacement} Replace first match of $substring with $replacement |
Is it the $page_text where you want to escape quotes?
Because there are two types of quotes to escape, you could do it like this: page_text="${page_text//\'/\'}" page_text="${page_text//\"/\\\"}" or page_text=$(GET domain | sed 's/['"'"'"]/\\&/g') Notice the sed command. MySQL isn't alone in not liking embedded quotes. I had to break up the sed command so that the shell wouldn't balk. Here I'll add some extra spaces so that it is clearer: Code:
sed 's/[' "'" '"]/\\/&/g' example demo: Code:
jschiwal@hpamd64:~> GET domain Code:
jschiwal@hpamd64:~> page_text="$(GET domain)" |
Guys - thanks very much for the help there. Some very tricky syntax!
|
Heh, you can actually just use php if you'd like to,
Code:
#!/usr/bin/php |
All times are GMT -5. The time now is 07:48 AM. |