如何从 sh 脚本中获取 `wget` 的 return 值到 `int` 变量中
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
棋盘:Raspberry Pi 4
我有一个脚本:
#!/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
我使用 C++ 程序调用:
int val_system = 0;
val_system = system("/var/www/html/4panel/get_page.sh");
std::cout<<"System return value: "<<val_system<<std::endl;
如果脚本有问题,echo "$?"
会输出wget
的return值,但val_system
永远是0。
system()
return 是 echo "$?"
的值吗?在这种情况下 0 是正确的。如果是这种情况,我如何将 wget
的 return 值放入 val_system
中?
我遇到过echo "$?"
总是returns 8的情况,基本上我输入了不正确的URL和:
- 我已经尝试删除
echo "$?"
但 val_system
仍然 returned 0;
- 删除
echo "$?"
后,我已将 wget
行更改为 wget -q -i "$line" -O $file --timeout=2
和 val_system
现在 returns 2048.
None 我的尝试没有结果,我来这里寻求指导。我怎样才能使 val_system
/ system()
return 变成什么 echo "$?"
return?
如何从脚本中获取 wget
的 return 值到调用脚本的 C++ 程序中的 int
变量?
如果你想回显状态 和 return 它,你需要将 $?
的值保存到一个变量中,然后退出它明确。
wget_output=$(wget -q -i "$line" -O $file --timeout=2)
status=$?
...
echo $status
...
exit $status
如果您不需要在调用 wget
和脚本结束之间执行 echo
或任何其他命令,您可以依赖脚本以最后状态退出 (即对应于隐式调用 `wget) 的那个。
返回的整数值 system()
包含有关已执行命令状态及其退出代码的额外信息,请参阅 system() and Status Information。您需要使用 WEXITSTATUS
宏提取退出代码,例如:
std::cout << "System return value: " << WEXITSTATUS(val_system) << std::endl;
OS:Linux raspberrypi 4.19.58-v7l+ #1245 SMP Fri Jul 12 17:31:45 BST 2019 armv7l GNU/Linux 棋盘:Raspberry Pi 4
我有一个脚本:
#!/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
我使用 C++ 程序调用:
int val_system = 0;
val_system = system("/var/www/html/4panel/get_page.sh");
std::cout<<"System return value: "<<val_system<<std::endl;
如果脚本有问题,echo "$?"
会输出wget
的return值,但val_system
永远是0。
system()
return 是 echo "$?"
的值吗?在这种情况下 0 是正确的。如果是这种情况,我如何将 wget
的 return 值放入 val_system
中?
我遇到过echo "$?"
总是returns 8的情况,基本上我输入了不正确的URL和:
- 我已经尝试删除
echo "$?"
但val_system
仍然 returned 0; - 删除
echo "$?"
后,我已将wget
行更改为wget -q -i "$line" -O $file --timeout=2
和val_system
现在 returns 2048.
None 我的尝试没有结果,我来这里寻求指导。我怎样才能使 val_system
/ system()
return 变成什么 echo "$?"
return?
如何从脚本中获取 wget
的 return 值到调用脚本的 C++ 程序中的 int
变量?
如果你想回显状态 和 return 它,你需要将 $?
的值保存到一个变量中,然后退出它明确。
wget_output=$(wget -q -i "$line" -O $file --timeout=2)
status=$?
...
echo $status
...
exit $status
如果您不需要在调用 wget
和脚本结束之间执行 echo
或任何其他命令,您可以依赖脚本以最后状态退出 (即对应于隐式调用 `wget) 的那个。
返回的整数值 system()
包含有关已执行命令状态及其退出代码的额外信息,请参阅 system() and Status Information。您需要使用 WEXITSTATUS
宏提取退出代码,例如:
std::cout << "System return value: " << WEXITSTATUS(val_system) << std::endl;