pcgben
pcgben

Reputation: 756

Pipe cat/grep/arguments into variable in bash script

#!/bin/bash
DATE=`date +%Y-%m-%d`
HOUR=`date +%H`
ORDERS_THIS_HOUR=`cat cli.log | grep $DATE $HOUR | grep -o "generated for Production" | wc -l`
OUTPUT="$DATE $HOUR : $ORDERS_THIS_HOUR"

echo "$OUTPUT" >> flow_productivity.log

Issue is with the second line: grep: 14: No such file or directory.

Here is a sample command, the results of which I would like to store in $ORDERS_THIS_HOUR:

cat cli.log | grep "2019-02-13 12" | grep -o "generated for Production" | wc -l

Run from the command line, the above produces the expected output.

Upvotes: 2

Views: 2981

Answers (2)

Charles Duffy
Charles Duffy

Reputation: 295363

First -- because you aren't putting quotes around your expansions, they're passed as separate arguments to grep. The first result of string-splitting and globbing $DATE $HOUR becomes the filename that grep searches through, and subsequent ones become filenames to search.

Beyond that, it's a bad idea to call date more than once in the same script anyhow. What if your script is run as the time passes midnight? You could have the first call to date be for the end of one day, and the second one return the very beginning of the next morning. To avoid this risk, call date only once, as in the following:

now=$(date '+%Y-%m-%d %H')
msg="generated for Production"
orders_this_hour=$(grep -Ec "($now.*$msg|$msg.*$now)" <cli.log)
output="$now : $orders_this_hour"
echo "$output" >> flow_productivity.log

Upvotes: 1

deosha
deosha

Reputation: 992

It is taking $HOUR as filename. Make it grep "$DATE $HOUR"

Upvotes: 1

Related Questions