ECHOING VARIABLES AND COMMANDS
- now type
MYSECRET="I'm learning to code"
. This will actually store the words "I'm learning to code" in the variable MYSECRET
. You might now THINK the we can find out that variable by typing echo MYSECRET
. But if you try this (go ahead, it won't hurt anything), you'll find that it won't echo back I'm learning to code
, but, rather MYSECRET
. So what can we do? If you were solving this problem yourself, what would you do? You'd probably want to be able to tell the computer, "look, I don't literally want you to echo the words 'MYSECRET'; I want you to give me what MYSECRET
refers to." While some mildly amusing vaudeville humor derives from overly-literal responses to requests, this isn't what we want here. So to let the computer know that we don't want the 'literal' MYSECRET
back (and computer science uses the term literal
here just the way we do). but rather the variable MYSECRET
, we're going to put a $
at the front, typing the full command echo $MYSECRET
. Hopefully you'll hear back I'm learning to code
from the machine.
- so it's cool that you can add variables to the end of a string of words (or just a "string"), but what if we wanted to insert the date? We might WANT to type
echo "the current date and time are $date"
, right? This would put together what we learned in the previous step with what we just learned about variables. But this can't work--can you see why? Go ahead and type it. What do you see? The computer is looking for a VARIABLE called date
, and you haven't defined it yet. If you were to type date="not really a date"
, you could then go back (up arrow) and re-enter echo "the current date and time are $date"
, and you would see the current date and time are not really a date
. So how do we get the behavior we want? In addition to telling the computer not to take the word date
literally, we also need to indicate that date
here is the command date
and not just a variable. And we'll do this by adding parentheses around date, making the full command echo "the current date and time are $(date)"
. This should give you the expected behavior.
- note that the
$
and the ()
are somewhat arbitrary. The developers that made the shell could have chosen different symbols. But they needed to use SOME sorts of symbols here--there was no other option. And this is why when learning any new language, we need to learn (and rigorously adhere to) its syntax.