1

This is the code i use, i want to collect data from 4 logfile(s) in one file, then sort it and print the temp filename.

#!/bin/bash

TEMPFILE=$(mktemp)
USER=$1

# Check for input
#if [ -z $1 ]; then echo "Give me one username or mail address please..."

# Fill file with user history
cat /var/log/messages | grep $USER >> $TEMPFILE
cat /var/log/maillog | grep $USER >> $TEMPFILE
zcat /var/log/messages*gz | grep $USER >> $TEMPFILE
zcat /var/log/maillog*gz | grep $USER >> $TEMPFILE

# Sort by date
cat $TEMPFILE | sort -k1M -k2n -k3n > $TEMPFILE

echo $TEMPFILE

1 Answer 1

1

cat and zcat everywhere are useless and you cannot redirect to same file you're reading, that will get you a 0 byte file.

Try this:

#!/bin/bash

TEMPFILE=$(mktemp)
user="$1"

# Check for input
#if [ -z $1 ]; then echo "Give me one username or mail address please..."

# Fill file with user history
grep "$user" /var/log/messages >> $TEMPFILE
grep "$user" /var/log/maillog >> $TEMPFILE
zgrep "$user" /var/log/messages*gz >> $TEMPFILE
zgrep "$user" /var/log/maillog*gz >> $TEMPFILE

# Sort by date
sort -k1M -k2n -k3n "$TEMPFILE" > "$TEMPFILE.tmp"
mv "$TEMPFILE.tmp" "$TEMPFILE"

cat "$TEMPFILE"

PS: Don't use upper case USER as variable run otherwise you will overwrite shell provide value for this variable. In general it is not recommended to use all uppercase variables in your script.

Sign up to request clarification or add additional context in comments.

2 Comments

You could do both grep in one command, same with zgrep and you could mess with stdout so you don't get multiple opens, but it would make the script more difficult to read and I doubt it would save you much, if anything. Only other thing, the question wants to print the temporary file name but you print (cat) the file itself.
Thanks for your suggestions. Last echo wasn't serving any purpose as that could be done right after mktemp command. I assumed OP wants to see the final output that's why cat instead of echo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.