Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I need to use the result of a formatted date command (date +"%m/%d") as the grep filter to filter the results of another command that will display alerts on a system so that I only see alerts from the given day.

Lets say alertcommand gives the alert readout in the console. I know I can do alertcommand | grep 8/10 to get the logs from today, but I want to be able to feed date +"%m/%d"into that so that I don't have to specify the date each time I run it, but I can't figure out how to link it into one single command (preferably without having to create temp files or anything as this will be run on customer hardware).

I looked at this question that was similar, but couldn't figure out how to make it work the same way.

share|improve this question

3 Answers 3

up vote 4 down vote accepted

In bash, just use something like alertcommand | grep $(date +"%m/%d")

$() executes a command in a subshell and returns the output of the command as string. Alternatively you can enclose the command with backticks to the same effect.

share|improve this answer
    
This worked, seems I was just missing the format of how to write it out from the other question I noted. I prefer to use $() as it is the more modern implementation. –  MaQleod Aug 10 '11 at 21:16

In FreeBSD's shell csh I can't use both of yours methods.

1)

cat /var/log/exim/mainlog | grep $(date +%Y-%m-%d)
Illegal variable name.

2)

d=`date +%Y-%m-%d`;cat /var/log/exim/mainlog|grep $d
d=2011-11-13: Command not found.

But I can use directly backticked code like this:

cat /var/log/exim/mainlog | grep `date +%Y-%m-%d`
share|improve this answer
1  
csh is harmful, stop using it. faqs.org/faqs/unix-faq/shell/csh-whynot –  Chris Down Nov 14 '11 at 12:35

You could simply assign the output of your date command to another variable, and use that as an argument:

myDateVariable=`date +"%m/%d"`
alertcommand | grep $myDateVariable

This way, you could re-use the date value in the future and also debug any intermediate steps

share|improve this answer
    
Not as useful to me as a single line command, but still a valid method. –  MaQleod Aug 10 '11 at 21:17
    
You can always separate them via a semicolon. For example, you could say myDateVariable=`date +"%m/%d"`; alertcommand | grep $myDateVariable –  Sudipta Chatterjee Aug 11 '11 at 8:19

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.