How to format date output with spaces as variable in script?
The reason your example fails is because of the way the shell's word splitting works. When you run "$($nice_date)"
, the shell is executing the date
command with two arguments, "+%Y-%m-%d"
and "%H:%M:%S"
. This fails because the format string for date must be a single argument.
The best way to do this is to use a function instead of storing the command in a variable:
format_date() {
# echo is not needed
date "+%Y-%m-%d %H:%M:%S" "$1"
}
format_date
format_date "2015-09-17 16:51:58"
echo "$(format_date) [WARNING] etc etc"
If you really wanted to store the command in a variable, you can use an array:
nice_date=(date "+%Y-%m-%d %H:%M:%S")
# again echo not needed
"${nice_date[@]}" "2015-09-17 16:51:58"
For more details on the complex cases of storing a command in a variable, see BashFAQ 050.
I agree a function is the best way to go. As an alternative simply store the format as a variable rather than the whole command:
$ nice_date='+%Y-%m-%d %H:%M:%S'
$ echo "$(date "$nice_date") [WARNING] etc etc"