Bash – command substitution within single quotes for alias

aliasbashcommand-substitution

Double quotes are required in bash for command substitution:

$ echo "$(date)"
Fri Oct 28 19:16:40 EDT 2016

Whereas single quotes do not do command substitution:

$ echo '$(date)'
$(date)

… why then do I see the following behavior with alias that seems to suggest that command substitution happened with single quotes?

alias d='$(date)'
$ d
No command 'Fri' found, did you mean:
   ....

Best Answer

Single-quote vs double-quote versions

Let's define the alias using single-quotes:

$ alias d='$(date)'

Now, let's retrieve the definition of the alias:

$ alias d
alias d='$(date)'

Observe that no command substitution was yet performed.

Let's do the same, but this time with double-quotes:

$ alias d="$(date)"
$ alias d
alias d='Fri Oct 28 17:01:12 PDT 2016'

Because double-quotes are used, command substitution was performed before the alias was defined.

Single-quote version

Let's try executing the single-quote version:

$ alias d='$(date)'
$ d
bash: Fri: command not found

The single-quote version is equivalent to running:

$ $(date)
bash: Fri: command not found

In both cases, the command substitution is performed when the command is executed.

A variation

Let's consider this alias which uses command substitution and is defined using single-quotes:

$ alias e='echo $(date)'
$ e
Fri Oct 28 17:05:29 PDT 2016
$ e
Fri Oct 28 17:05:35 PDT 2016

Every time that we run this command, date is evaluated again. With single-quotes, the command substitution is performed when the alias is executed, not when it is defined.

Related Question