i am writing a bash script in which i am storing current date in a variable and then i am greping that variable . issue is its not working

currentdate= $(date +%b\ %d) echo "$currentdate" last |grep -E '$currentdate'>> /usr/IBM/HTTPServer7/logs/alert/users.txt

users.txt is showing empty . if i write mannualy the current date then it works what am i doing wrong?

closed as off-topic by Sparhawk, G-Man, roaima, Kusalananda, Christopher Dec 4 '18 at 16:44

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions describing a problem that can't be reproduced and seemingly went away on its own (or went away when a typo was fixed) are off-topic as they are unlikely to help future readers." – Sparhawk, G-Man, Kusalananda
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 4
    Single quotes ' vs. double quotes ". The former won't expand variables. – Sparhawk Dec 4 '18 at 5:58
  • 2
    remove that space between = and $ in currentdate. and date syntax in last is like DEC 1 . that date command returns DEC 01 – BlackCrystal Dec 4 '18 at 6:26
  • 1
    Possible duplicate of When is double-quoting necessary? – roaima Dec 4 '18 at 8:56

In addition to the quotes, you also need to account for the date format used by the last command, which looks like the following:

Dec  3    # Note the padding to the left of '3'.
Nov 23

This requires a slightly different date command:

date "+%b %_d"
Dec  4

The underscore instructs date to pad the field with spaces. You can also use %e as an alternative.

Putting these together, you can modify your script as shown below:

currentdate=$(date "+%b %_d")
last | grep "$currentdate" >> /usr/IBM/HTTPServer7/logs/alert/users.txt

@Sparhawk is correct.

Double quotes cause the shell to expand variables.

$ VAR=blahblah
$ echo "$VAR"

Single quotes cause the shell to use the text literally.

$ VAR=blahblah
$ echo '$VAR'

You would use this if you wanted to prevent the shell from thinking a dollar sign plus some other text was a variable.

echo 'This script is terminating because you didn't set $IMPORTANT_VARIABLE'

Without single quotes the above message wouldn't output properly.

  • Issue is with this command all though currentdate has correct value which is today Dec 04 but in users.txt the file is empty . last |grep -E '$currentdate'>> /usr/IBM/HTTPServer7/logs/alert/users.txt if i use actual value Dec 04 in the above command the result is fine . – Black Virus Dec 4 '18 at 6:29

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