echo date question

Whats the difference between using date in these 2 methods? How exactly does the shell handle the first one different from the second one?

$ echo $date

$ echo $(date)
Tue Aug 16 03:10:25 EDT 2011
% echo $date

% date=qwerty

% echo $date
qwerty

% date
Tue Aug 16 14:25:38

% echo `date`
Tue Aug 16 14:25:53

% echo $(date)
Tue Aug 16 14:25:58

% echo $(whoami)
yazu

The first command prints the contents of the shell variable date. In your example it is empty.

The second command executes the command date in a subshell and then print the output of the date command. The result is identical to just running the date command by itself.

Thank you :). Remind me what these `` do please. What are they called?

Backticks... they're essentialy the same. $() is the preferred method nowadays as it creates cleaner commands, though some very old shells do not support it.

As a rule of thumb use $() everytime when possible, unless there is a good reason forcing you to use backticks.

Example:

# Using $():
[root@atlas]# a=$(date)
[root@atlas]# echo $a
Tue Aug 16 09:35:38 CDT 2011

# Produces the same as ``
[root@atlas]# a=`date`
[root@atlas]# echo $a
Tue Aug 16 09:35:51 CDT 2011

# Nested $() looks clean and it's easy to read:
[root@atlas]# a=$(date $(echo "-u" $(echo "+%T")))
[root@atlas]# echo $a
14:41:48

# Whereas nested `` looks weird and sloppy:
[root@atlas]# a=`date \`echo "-u" \\\`echo "+%T"\\\`\``
[root@atlas]# echo $a
14:42:09

Get into the habit of using $( ) as it handles nesting commands where using backticks for nested commands will get ugly fast. Fugly even.

Consider this exercise in futility using the korn shell:

$ echo `echo hello`
hello
$ echo `echo hello  `echo there``  #  Trouble nesting
helloecho there
$ echo `echo hello  \`echo there\``  # Getting ugly
hello there
$ echo $(echo Hello $(echo there))  # Handles nesting
Hello there
$

This page shows some real-world examples: [Chapter 45] 45.31 Nested Command Substitution

Gary