简体   繁体   中英

Bash Script Output to console and file

I need a small script to search for a string in log files and count the numbers of lines. Because this may take i while, i also want the output of "grep" shown in console. my idea is something like:

grep -irl "System out of memory" | tee /tmp/checkoom.tmp
COUNT=(cat /tmp/checkoom.tmp |wc -l)
echo $COUNT logs found.

But it dont works. I dont get any output, the tmp file is created but seems to be empty.

您忘记了提供搜索的起始目录:

grep -irl "System out of memory" <somewhere> | tee /tmp/checkoom.tmp

Here is the one liner for getting usb records from /var/log/messages:

echo "$(grep -i '/lib/udev/usb' /var/log/messages > ~/yourFile ; cat ~/yourFile | wc -l ) logs found"

Hope you find it usefull

There are two mistakes in the script:

  • The path to grep
  • $() is used to execute a command. This has to be added when assigning variable COUNT

Updated script:

#!/bin/bash
grep -irl "System out of memory" <path to search> | tee /tmp/checkoom.tmp
COUNT=$(cat /tmp/checkoom.tmp | wc -l)
echo "$COUNT" logs found.

Also you could use the -F option in grep. -F stands for Fixed Strings

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM