Bash – How to escape single or double quotes when passing a variable to bash script

bashquotingshellstring

Let's say I have a script which echoes $1

#!/bin/bash
echo $1

It's called test.sh.
Then I call /bin/test.sh 'test'. The output is test. But this doesn't work:

/bin/test.sh 'te'st'

There's a syntax error.

There can be anything between those two single quotes, e.g.

/bin/test.sh 'te"s"t'` or `/bin/test.sh 'te's't'` or `/bin/test.sh 'te"s't'

Is there a way to deal with this? I can work only with enclosing quotes. I can't alter what is inside the variable; it's a log parsing. Anything can be inside a log entry.

I need for bash to take those arguments correctly.

Example:

/bin/test.sh '2015.11.11 07:45:44.060|executor-2|||ERROR|236 - PDF document for 5616904 wasn't created!'

This doesn't work because of the single ' in the word wasn't inside the string.

The string is beeing placed exactly as I wrote it. I am using it with Zabbix (monitoring solution). So in zabbix it's something like this:

/bin/test.sh '{$TRIGGER.VALUE}'

But in the end {$TRIGGER.VALUE} is replaced with the actual string and script is called with literal value.

Best Answer

Your approach is fundamentally flawed. You grind the meat into hamburger for transportation, and then you want to get the cow back at the end. Nope, that doesn't work.

Instead of injecting the string directly into the shell command, pass it as an argument. I'm not familiar with Zabbix, but looking at the documentation, this appears to be how it works (e.g. external checks, user parameters: you specify a command, and the arguments that it takes. So specify just test.sh as the command, and specify that the parameter that it gets is that "{TRIGGER.VALUE}". Apparently (once again, I'm not familiar with Zabbix), this means you write something like

test.sh["{TRIGGER.VALUE}"]

In test.sh, to refer to the argument of the script, remember that you need to write "$1", not $1.