I’m creating a script to detect which user didn’t connect to the server for a while.
So far everything is good but now trying to remove some unwanted entry from the list produced from my script. I would like to add an exception to my script so that when lastlog is called with a non used argument, the ouput isn’t printed to the screen.
I’ve tried somthing like :
if [ $? -gt 0 ]; then
echo "ERROR!"
fi
But the problem is that lastog is returning 0 on success but simply :
lastlog: Unknown user or range: infolog
on error. So I cannot catch the exeption.
Here’s my code (which is pretty simple)
#!/bin/bash
FILES=../*
for year in 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012
do
for f in $FILES
do
tempUser=${f:3:20}
userCommand=`lastlog -u $tempUser | grep $year`
if [ ${#userCommand} != 0 ]
then
echo "$userCommand"
fi
done
done
You can test this pretty simply, but on my handy linux box
lastlogdoes indeed set a nonzero status for a bad user name:If you’re running this in a pipe, the problem is that the “status” of a pipe sequence is the status of the last element of the pipeline:
prints the status for progC.
If you use bash, you can get the status from everything via bash’s
PIPESTATUSarray variable:which should get you the rest of the way there.
Edit: you might not even care, and just be looking for a way to throw away stderr output from
lastlog, in which case, consider: