forenbuddy forenbuddy - 1 year ago 70
Bash Question

QT program containing a bash script with an if-test-then block and the escaped necessary quotes inside issues error

I am trying to run a small bash script inside a QT application which contains an if-test-then block and the necessary quotes inside the test. As the script should be compiled by QT and run by bash, the quotes have to be escaped twice, so the escaping backslashes for the quotes have to be escaped also, as I see it. Unfortunately it does not work as expected.

Here is the code:

#include <stdio.h>

QObject *parent;

int main(int argc, const char* argv[])
QProcess *myProcess = new QProcess(parent);
myProcess->execute("/bin/bash -c \"x=1 ; echo $x ; if [ \\\"$x\\\" = \\\"1\\\" ] ; then echo itsOne ; fi\"");

when I run the compiled program, I get the output:

root@debian:~# ./proggy
/bin/bash: line 0: [: missing `]'

instead of the output seen here, when trying the same script in a bash terminal:

root@debian:~# x=1 ; echo $x ; if [ "$x" = "1" ] ; then echo itsOne ; fi

I have tried all sorts of combinations of escapes and quotes in the QT-program, nothing has helped so far.

Does anybody know, what is wrong here or how to solve this riddle? Somehow it looks like the escaped quotes inside the test command break up the script seen by the bash. Why would bash not see the closing bracket if there are two necessary quotes inside the test command?

Answer Source

A couple of points.

Firstly execute is a static member of QProcess so there's no need to create an instance of QProcess.

Secondly, it's generally easier to use the execute overload that separates the program name from the argument list.

With that in mind what you want is probably something like...

QProcess::execute("/bin/bash", QStringList() << "-c" << "x=1 ; echo $x ; if [ \\\"$x\\\" = \\\"1\\\" ] ; then echo itsOne ; fi");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download