linux - Running multi-line bash script as string from C++ code -


i want run following bash script c++ code. tries use system() or popen run commands , capture output errors because built-in sh tries execute it, such as,

sh: 6: [[: not found sh: 8: [[: not found sh: 9: [[: not found 

i tried bash -c produced errors because think doesn't handle multiline string.

i can't put below script in .sh file , run because of several reasons. script needs stored string in c++ code , executed. idea how can done?

#!/bin/bash sysdevpath in $(find /sys/bus/usb/devices/usb*/ -name dev);     (         syspath="${sysdevpath%/dev}"         devname="$(udevadm info -q name -p $syspath)"         [[ "$devname" == "bus/"* ]] && continue         eval "$(udevadm info -q property --export -p $syspath)"         [[ -z "$id_serial" ]] && continue         [[ "${id_serial}" == *"px4"* ]] && echo "/dev/$devname"     ) done 

sample code:

note: can use this tool convert text c++ escapped string.

int main() {     std::cout << system("#!/bin/bash\nfor sysdevpath in $(find /sys/bus/usb/devices/usb*/ -name dev); do\n    (\n        syspath=\"${sysdevpath%/dev}\"\n        devname=\"$(udevadm info -q name -p $syspath)\"\n        [[ \"$devname\" == \"bus/\"* ]] && continue\n        eval \"$(udevadm info -q property --export -p $syspath)\"\n        [[ -z \"$id_serial\" ]] && continue\n        [[ \"${id_serial}\" == *\"px4\"* ]] && echo \"/dev/$devname\"\n    )\ndone");      return 0; } 

you can turn multiline script single-line. let's assume have following script:

foo=`uname` if [ "$foo" == "linux" ];     echo "you using 'linux'" fi 

the code above can transformed single-line using semicolons:

foo=`uname`; if [ "$foo" == "linux" ]; echo "you using 'linux'"; fi 

now proper escaping can use system command execute program follows:

#include <cstdlib> #include <string>  int main() {     std::string foo {         "bash -c '"         "foo=`uname`; "         "if [ \"$foo\" == \"linux\" ]; "         "echo \"you using 'linux'.\"; "         "fi'"     };     system(foo.c_str()); } 

note adjacent string literals concatenated compiler, can still make multiline script better readability.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -