1

Want to pass the current month to grep so it lists current month's logins for a specific user. Script below does echo the current month, ($mnth), but grep doesn't do anything with it. If I hard code the month("Sep") instead of $mnth, I get the correct output - last month of logons. I guess working solution should apply to the year "2020" also.

#!/bin/bash                                                                                       
echo -e '\n'                                                                              
echo $SHELL                                                                                        
echo -e '\n'   
mnth=$(date +%b)                                                                   
echo $mnth                                                                          

last -F john_paul_jones | grep -E '$mnth ([ 1-9]|1[0-9]|2[0-9]|30)' | grep 2020 |more

Thanx

RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • 1
    use double quotes if you want $mnth to resolve in the grep expression. single quote tell the command interpreter not to replace $var with its value try echo '$mnth' and echo "$mnth" to see the difference – Rob Sep 02 '20 at 20:35
  • 1
    You should almost always double-quote variable references (e.g. `echo "$SHELL"` instead of `echo $SHELL`) (and, as Rob said, *don't* single-quote them). [shellcheck.net](https://www.shellcheck.net) is good at spotting common mistakes like this. – Gordon Davisson Sep 02 '20 at 20:41
  • Shellcheck.net is preety coool. Not many people were I work are very good at bash scripting. I enclosed $mnth in double quotes, Got the same result (grep didn't do anything with it, no results). Shellcheck.net had a line just below with an arrow pointing to '"$mnth" saying "expressions don't expand in single quotes, use double quotes instead". But I did use double quotes... – MeatPopsicle Sep 03 '20 at 14:46

0 Answers0