Linux打印状态检查脚本

时间:2014-10-24 18:50:29

标签: linux bash shell printing conditional

我试图编写一个检查打印机状态的脚本(它将被设置为chron作业)。如果打印机正在运行,它将显示打印机已启用。如果打印机不是,它应该发送带有lpstat信息的电子邮件。无论哪种方式,它应该将lpstat信息写入txt文件,该文件仅在打印机关闭的情况下通过电子邮件发送。这是脚本:

#This script is designed to check the status of a printer.
#The printer's status attributes will be written to a text file.
#Finally, ane mail will be sent from the command line containing the text file.
lpstat -t -h <host name> -p <printer name> > /tmp/printerstatus.txt
RC=cat /tmp/printerstatus.txt | grep "enabled"
if [ -z $RC ]
then
mail -s "Printer Status" ****.********@******.com < /tmp/printerstatus.txt
else
echo "Printer Enabled";
fi

以下是我遇到的错误:

/tmp/printerstatus.txt: line 1: scheduler: command not found
/tmp/printerstatus.txt: line 2: system: command not found
/tmp/printerstatus.txt: line 3: device: command not found
/tmp/printerstatus.txt: line 4: <printer name>: command not found
/tmp/printerstatus.txt: line 5: printer: command not found
/tmp/printerstatus.txt: line 6: Paused: command not found
/tmp/printerstatus.txt: line 7: printer: command not found
/tmp/printerstatus.txt: line 8: Paused: command not found
./checkprinter.sh: line 12: syntax error: unexpected end of file

我试图从/ home目录运行脚本。提前感谢您的建议:)

2 个答案:

答案 0 :(得分:2)

这一行

RC=cat /tmp/printerstatus.txt | grep "enabled"

尝试执行/tmp/printerstatus.txt(为什么将其执行权限设置?)作为shell脚本。您希望使用命令替换来捕获变量cat中整个管道的输出(顺便说一句,这是对RC的无用使用)。

RC=$(grep "enabled" /tmp/printerstatus.txt)

您可以将脚本进一步缩小为

if lpstat -t -h <host name> -p <printer name> | tee /tmp/printerstatus.txt | grep -q "enabled"; then
    mail -s "Printer Status" ****.********@******.com < /tmp/printerstatus.txt
else
    echo "Printer Enabled";
fi

答案 1 :(得分:2)

RC=cat /tmp/printerstatus.txt | grep "enabled"

这导致了错误。

grep的第二个参数是文件名。 cat to to grep是多余的。你应该

RC=$(grep "enabled" /tmp/printerstatus.txt)