Jason S Jason S - 7 days ago 4x
Bash Question

Using quotes within command substitution

I don't understand why this works

dateCMD=$(date -d "4 hours ago")
echo $dateCMD
Tue Oct 18 02:20:34 AEDT 2016

and this works

Tue Oct 18 06:23:19 AEDT 2016

But not this

dateCMD='date -d "4 hours ago"'
date: extra operand ‘ago"’

How can I get this last case to work?


Short answer: you don't want to do that. Use a function instead.

dateCMD () {
  date -d "4 hours ago"


Long answer: quotes in the value of a parameter are not "syntactic" quotes; they are just regular data. When you write

dateCMD='date -d "4 hours ago"'

It is evaluated as follows:

  1. $dateCMD expands to date -d "4 hours ago"
  2. The expansion is split into the words date, -d, "4, hours, and ago". The quotes are not treated specially.
  3. The first word, date, is treated as the command with the rest of the words passed as distinct arguments.
  4. date treates "4 as the argument to the -d option. Since date takes only one additional positional argument (the format string), it takes hours as that argument, then complains that ago is an extra operand.