Search code examples
c++bashshellsystem

How can I get the return value of `wget` from a sh script into an `int` variable


OS: Linux raspberrypi 4.19.58-v7l+ #1245 SMP Fri Jul 12 17:31:45 BST 2019 armv7l GNU/Linux Board: Raspberry Pi 4

I have a script:

#!/bin/bash

line=$(head -n 1 /var/www/html/configuration.txt)
file=/var/www/html/4panel/url_response.txt
if [ -f "$file" ]; then
    wget_output=$(wget -q -i "$line" -O $file --timeout=2)
    echo "$?"
else
    echo > $file
    chown pi:pi $file 
fi

which I call from a C++ program using:

int val_system = 0;
val_system = system("/var/www/html/4panel/get_page.sh");
std::cout<<"System return value: "<<val_system<<std::endl;

If there is something wrong with the script, echo "$?" will output the return value of wget, but val_system will always be 0.

Does system() returns the value of echo "$?" ? In which case 0 is correct. And if that is the case how can I put the return value of wget in val_system ?

I have taken a situation in which echo "$?" always returns 8, basically I've entered an incorrect URL and:

  • I have tried deleting echo "$?" but val_system still returned 0;
  • With echo "$?" deleted I have changed the wget line to wget -q -i "$line" -O $file --timeout=2 and val_system now returns 2048.

None of my attempts bared any fruit and I have come here to seek guidance. How can I make val_system / system() return what echo "$?" returns ?

How can I get the return value of wget from the script into an int variable that's inside the C++ program that calls the script ?


Solution

  • The integer value system() returned contains extra information about executed command's status along with its exit code, see system() and Status Information. You need to extract exit code using WEXITSTATUS macro, like:

    std::cout << "System return value: " << WEXITSTATUS(val_system) << std::endl;