Bash - Date command and space
The correct approach is to define your own function inside your Bash script.
function my_date {
date "+%y-%m-%d %H:%M:%S"
}
Now you can use my_date
as if it were an external program.
For example:
echo "It is now $(my_date)."
Or simply:
my_date
Why isn't your approach working?
The first problem is that your assignment is broken.
DATE_COMMAND="date "+%y-%m-%d %H:%M:%S""
This is parsed as an assignment of the string date +%y-%m-%d
to the variable DATE_COMMAND
. After the blank, the shell starts interpreting the remaining symbols in ways you did not intend.
This could be partially fixed by changing the quotation.
DATE_COMMAND="date '+%y-%m-%d %H:%M:%S'"
However, this doesn't really solve the problem because if we now use
echo $($DATE_COMMAND)
It will not expand the argument correctly. The date
program will see the arguments '+%y-%m-%d
and %H:%M:%S'
(with quotes) instead of a single string. This could be solved by using eval
as in
DATE_COMMAND="date '+%y-%m-%d %H:%M:%S'"
echo $(eval $DATE_COMMAND)
where the variable DATE_COMMAND
is first expanded to the string date '+%y-%m-%d %H:%M:%S'
that is then eval
uated as if it were written like so thus invoking date
correctly.
Note that I'm only showing this to explain the issue. eval
is not a good solution here. Use a function instead.
PS It is better to avoid all-uppercase identifier strings as those are often in conflict with environment variables or even have a magic meaning to the shell.
Escaping the space works for me.
echo `date +%d.%m.%Y\ %R.%S.%3N`