0

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 it's 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 manually the current date then it works. What am I doing wrong?

Qohelet
  • 507

2 Answers2

1

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
Haxiel
  • 8,361
0

@Sparhawk is correct.

Double quotes cause the shell to expand variables.

$ VAR=blahblah
$ echo "$VAR"
blahblah

Single quotes cause the shell to use the text literally.

$ VAR=blahblah
$ echo '$VAR'
$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.

LawrenceC
  • 10,992
  • 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 04 '18 at 06:29