LPI Linux Essentials Variable Question

Have a look at this question on the screenshot.  
user_407565_5c204015687c2.png_800.jpg
I don't understand why my answer is wrong when, practically it works.  If I type at the console:
actdat=date 
hit enter and then type up:
$actdat
The date prints to standard output like this
user_407565_5c20409109ed8.png
So why is it, the answer to the question is:
actdat='date'


  • post-author-pic
    Kyle J
    12-24-2018

    Not certain myself, but it could be that because they want to force you to use the quotes as it is less error-prone and more convenient.


    E.g displaying the hour only, with quotes and without quotes:
       actdat='date %H'     vs     actdat=date\ '%H'

  • post-author-pic
    Jake W
    12-24-2018

    I can't tell for sure due to the photo's resolution, but those look like backticks rather than single quotes. The problem with both methods you described:

    actdate=date

    actdate='date'

    is that while both will work when invoked by themselves, they will not evaluate the value and store it in the variable.

    ====

    [cloud_user@jwickenhofer4c ~]$ actdate=date

    [cloud_user@jwickenhofer4c ~]$ $actdate

    Mon Dec 24 09:09:53 EST 2018

    [cloud_user@jwickenhofer4c ~]$ echo $actdate

    date

    ====

    When we pass the variable by itself, bash just sees the date command and runs it. However, when we pass it to another command, it just sees the string value "date." Backtick expansion, by contrast, will actually cause the contents between the backticks to be evaluated every time the variable is referenced:

    ====

    [cloud_user@jwickenhofer4c ~]$ actdate=`date`

    [cloud_user@jwickenhofer4c ~]$ echo $actdate

    Mon Dec 24 09:12:59 EST 2018

    ====

    The question still isn't 100% correct, however, because backtick expansion is actually deprecated, and parenthetical expansion is the correct way to utilize command substitution, like so:

    ====

    [cloud_user@jwickenhofer4c ~]$ actdate=$(date)

    [cloud_user@jwickenhofer4c ~]$ echo $actdate

    Mon Dec 24 09:16:34 EST 2018

    ====

    Backticks will still work but I've had some older scripts where certain things did not work correctly, and when changed to parentheses, worked perfectly.

Looking For Team Training?

Learn More