我正在编写脚本来下载一堆文件,并且我希望它在特定文件不存在时进行通知。检查wget的返回值[if]
r=`wget -q www.someurl.com`
if [ $r -ne 0 ]
then echo "Not there"
else echo "OK"
fi
但它给上执行了以下错误:
./file: line 2: [: -ne: unary operator expected
有什么不对?
我正在编写脚本来下载一堆文件,并且我希望它在特定文件不存在时进行通知。检查wget的返回值[if]
r=`wget -q www.someurl.com`
if [ $r -ne 0 ]
then echo "Not there"
else echo "OK"
fi
但它给上执行了以下错误:
./file: line 2: [: -ne: unary operator expected
有什么不对?
$r
是wget(您用反引号捕获的)的文本输出。要访问返回码,请使用$?
变量。
$r
为空,因此您的条件变为if [ -ne 0 ]
,并且好像-ne
被用作一元运算符。试试这个:
wget -q www.someurl.com
if [ $? -ne 0 ]
...
编辑安德鲁我之前解释的,反引号返回标准输出,而$?
返回上次操作的退出代码。
这是唯一的答案,它解释了提问者为什么会收到错误消息。 +1。 – lesmana 2013-01-02 21:25:07
其他人正确地贴,你可以用$?
来获得最新的退出代码:
wget_output=$(wget -q "$URL")
if [ $? -ne 0 ]; then
...
这使您可以同时捕获标准输出和退出代码。如果你不真正关心它所打印的,你可以直接测试它:
if wget -q "$URL"; then
...
如果你想抑制输出:
if wget -q "$URL" > /dev/null; then
...
你可以只
wget ruffingthewitness.com && echo "WE GOT IT" || echo "Failure"
-(~)----------------------------------------------------------(07:30 Tue Apr 27)
[email protected] [2024] --> wget ruffingthewitness.com && echo "WE GOT IT" || echo "Failure"
--2010-04-27 07:30:56-- http://ruffingthewitness.com/
Resolving ruffingthewitness.com... 69.56.251.239
Connecting to ruffingthewitness.com|69.56.251.239|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: unspecified [text/html]
Saving to: `index.html.1'
[ <=> ] 14,252 72.7K/s in 0.2s
2010-04-27 07:30:58 (72.7 KB/s) - `index.html.1' saved [14252]
WE GOT IT
-(~)-----------------------------------------------------------------------------------------------------------(07:30 Tue Apr 27)
[email protected] [2025] --> wget ruffingthewitness.biz && echo "WE GOT IT" || echo "Failure"
--2010-04-27 07:31:05-- http://ruffingthewitness.biz/
Resolving ruffingthewitness.biz... failed: Name or service not known.
wget: unable to resolve host address `ruffingthewitness.biz'
zsh: exit 1 wget ruffingthewitness.biz
Failure
-(~)-----------------------------------------------------------------------------------------------------------(07:31 Tue Apr 27)
[email protected] [2026] -->
非常聪明!我建议在命令行响应中添加'-q' – insign 2015-11-13 17:58:42
我一直在尝试所有的解决方案,但没有幸运。
wget以非交互方式执行。这意味着wget在后台工作,并且无法使用$?捕获返回代码。
一个解决办法是处理“--server响应”属性,搜索HTTP 200状态码 例如:
wget --server-response -q -o wgetOut http://www.someurl.com
sleep 5
_wgetHttpCode=`cat wgetOut | gawk '/HTTP/{ print $2 }'`
if [ "$_wgetHttpCode" != "200" ]; then
echo "[Error] `cat wgetOut`"
fi
注:wget的需要一些时间来完成他的工作,因为这个原因,我把“睡5”。这不是最好的方法,但可以用来测试解决方案。捕捉从wget的成果,并查看呼叫状态
wget -O filename URL
if [[ $? -ne 0 ]]; then
echo "wget failed"
exit 1;
fi
这样,您就可以检查的wget的状态以及存储输出数据
的最佳方式。
如果调用成功使用输出存储
否则会出错wget的退出失败
这是正确的方法。 – kSiR 2010-04-27 12:28:06
虽然这是正确的,但更好的解释是为什么'$ r'是空的,为什么会出现错误信息。 – Brian 2014-04-03 12:06:41