我正在尝试编写一个shell脚本,该脚本将通过以下输出检查备份是否成功,以通过邮件发送警报:
Server standby:
PostgreSQL: OK
is_superuser: OK
PostgreSQL streaming: OK
wal_level: Failed
replication slot: OK
directories: OK
retention policy settings: OK
backup maximum age: OK (no last_backup_maximum_age provided)
compression settings: OK
failed backups: OK (there are 0 failed backups)
minimum redundancy requirements: OK (have 96 backups, expected at least 0)
ssh: OK (PostgreSQL server)
pg_receivexlog: OK
pg_receivexlog compatible: OK
receive-wal running: OK
archiver errors: OK
以下是完成工作的简单shell脚本:
#!/bin/bash
OUT="Server standby:
PostgreSQL: OK
is_superuser: OK
PostgreSQL streaming: Failed
wal_level: OK
replication slot: OK
directories: OK
retention policy settings: OK
backup maximum age: OK (no last_backup_maximum_age provided)
compression settings: OK
failed backups: OK (there are 0 failed backups)
minimum redundancy requirements: OK (have 96 backups, expected at least 0)
ssh: OK (PostgreSQL server)
pg_receivexlog: OK
pg_receivexlog compatible: OK
receive-wal running: OK
archiver errors: OK"
if [ "`echo "$OUT" | sed -n '1!p' | grep -v 'OK'`" = "" ]
then
echo "Backup successful & nothing failed"
else
echo "$OUT" | sed -n '1!p' | grep -v 'OK'
fi
输出: ./check2.sh PostgreSQL流媒体:失败
有没有更好的方法来检查使用迭代或数组? 我试过这样的事情:
#!/bin/bash
OUT="Server standby:
PostgreSQL: OK
is_superuser: OK
PostgreSQL streaming: Failed
wal_level: OK
replication slot: OK
directories: OK
retention policy settings: OK
backup maximum age: OK (no last_backup_maximum_age provided)
compression settings: OK
failed backups: OK (there are 0 failed backups)
minimum redundancy requirements: OK (have 96 backups, expected at least 0)
ssh: OK (PostgreSQL server)
pg_receivexlog: OK
pg_receivexlog compatible: OK
receive-wal running: OK
archiver errors: OK"
#FAIL=$(echo "$OUT" | sed 's/:.*//' | sed -n '1!p')
for status in $(echo "$OUT" | cut -d ":" -f 2 | sed -n '1!p' | awk '{print $1}' )
do
if [ "$status" = 'OK' ]
then
echo "$status"
else
echo "$FAIL "-" $status"
fi
done
答案 0 :(得分:3)
egrep -v '^Server standby:$|: OK|^$' <<<"$OUT"
...只返回一行:
wal_level: Failed
因此,这可以很简单:
failures=$(grep -E -v '^Server standby:$|: OK|^$' <<<"$OUT")
if [[ $failures ]]; then
printf '%s\n' "$failures"
else
echo "Backup successful and nothing failed"
fi
也就是说,如果你想将输出的每一行添加到一个数组中(例如,通过检查数组长度来计算它们),这很容易做到:
mapfile -t failures < <(grep -E -v '^Server standby:$|: OK|^$' <<<"$OUT")
if (( ${#failures[@]} == 0 )); then
echo "No failures"
else
echo "Failures seen:"
printf ' - %s\n' "${failures[@]}"
fi
......我很难说这个更简单。