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
  • 497
  • 1
  • 5
  • 18
Black Virus
  • 21
  • 1
  • 1
  • 5
  • 4
    Single quotes `'` vs. double quotes `"`. The former won't expand variables. – Sparhawk Dec 04 '18 at 05: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 04 '18 at 06:26
  • 1
    Possible duplicate of [When is double-quoting necessary?](https://unix.stackexchange.com/questions/68694/when-is-double-quoting-necessary) – roaima Dec 04 '18 at 08:56

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,201
  • 1
  • 20
  • 30
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,884
  • 4
  • 33
  • 45
  • 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