linux - 关于 bash 脚本的虚假报告

标签 linux bash grep wget

上下文

我有一个脚本,它使用 wget 从网络服务器中提取数据,使用 ls -la 检查 index.html 页面的文件大小,如果它是使用 grep -o 确定大小,假定该页面无法满足客户要求。

代码

BADSERVER=()
FILE=SERVER
echo '' > $FILE.txt
<pull a list of hosts down>

if ! ssh -n -f $device -i <sshkey> "yes | rm index.* ; wget localhost:8080 ; ls -la index.html | grep -o 12282" > /tmp/$FILE 2> /dev/null; then
 echo "Unable to connect to $device"
 BADSERVER+=($device)
 echo '' > /tmp/$FILE
elif cat /tmp/$FILE | grep '12282' ; then
 echo 'Page is non functional to customer requirements on $device'
 BADSERVER+=($device)
 echo '' > /tmp/$device
else
 echo 'all is fine on $ip'
 echo '' > /tmp/$FILE
fi
done

问题

脚本报告某些网络服务器有文件大小,手动连接时我可以看到文件大小不一样。

脚本回溯

+ ssh -n -f webserver.1014 -i <omitted> 'yes | rm index.* ; wget localhost:8080 ; ls -la index.html | grep -o 12282'
+ grep 12282
+ cat /tmp/SERVER.txt
+ echo 'All OK on webserver.1014'
+ echo ''
+ cat /tmp/SERVER.txt

+ cat /tmp/SERVER.txt

+ ssh -n -f webserver.1015 -i <omitted> 'yes | rm index.* ; wget localhost:8080 ; ls -la index.html | grep -o 12282'
+ cat /tmp/SERVER.txt
+ grep 12282
12282
+ echo 'Page is non functional to customer requirements on $device'
Page is non functional to customer requirements on webserver.1015
+ BADSERVER+=($device)
+ echo ''
+ cat /tmp/SERVER.txt

+ cat /tmp/SERVER.txt

+ ssh -n -f webserver.1016 -i <omitted> 'yes | rm index.* ; wget localhost:8080 ; ls -la index.html | grep -o 12282'
+ cat /tmp/SERVER.txt
+ grep 12282
+ echo 'All OK on webserver.1017'
+ echo ''
+ cat /tmp/SERVER.txt

+ cat /tmp/SERVER.txt

webserver.1015的实际内容

-r--r--r--.  1 --- --- 25799 Mar 30 23:38 index.html

最佳答案

服务器是否在 webserver.1015 启动并运行?

为什么要使用 ; 而不是 &&

  • 如果前一个命令失败并返回 ;,第二个命令将运行。

  • 但是 && 第二个不会运行。

Don't parse the output of ls command.

使用 wget 仅提取文件大小

wget http://localhost:8080/index.html --spider --server-response -O - 2>&1 | sed -ne '/Content-Length/{s/.*://;p}'

或者用curl

size=$(curl -sI "http://localhost:8080/index.html"| awk '/Content-Length/{gsub("\\r", ""); 打印 $2} ')

关于linux - 关于 bash 脚本的虚假报告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49581952/

相关文章:

c - 从不同进程强制移除 fcntl 锁

正则表达式以使用 egrep 获取分隔内容

vim - 带括号和分号的 Grep/Ack 表达式

sed - 将新行视为另一个字符的 grep/sed 的替代方案

linux - 为什么 crond 无法在 alpine linux 上运行非根 crontab?

linux - fc 18 写入错误(文件系统已满?)

linux - 如何获取 EOF 标签内的变量值?

linux - 如何记录通过 ssh 发送的非交互式 bash 命令

python - 在线程崩溃时自动生成到 STDERR 的完整堆栈跟踪

linux - Bash shell 'if' 语句比较不同命令的输出