Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - Date command and space

Tags:

date

linux

bash

I am trying to create a script that uses the date command in bash. I am familiar with the basic syntax of the date command. Here is the simple script:

#!/bin/bash 
set -x 
DATE_COMMAND="date "+%y-%m-%d %H:%M:%S"" 
echo "$($DATE_COMMAND)" 
set +x

The thing is that the above code doesn't work. Here is the output:

+ DATE_COMMAND='date +%y-%m-%d'
+ %H:%M:%S
onlyDate: line 3: fg: no job control
+ echo ''

+ set +x

Ok, so the problem is that the bash splits the command because of the space. I can understand that but I don't know how to avoid that. I have tried to avoid the space with \, to avoid the space and the ". Also the single quotes doesn't seem to work.

Please note that I know that this script can be written this way:

#!/bin/bash
set -x
DATE_COMMAND=$(date "+%y-%m-%d %H:%M:%S")

echo "$DATE_COMMAND"
set +x

I have tried that but I can't use this approach because I want to run the command several times in my script.

Any help will be really appreciated!

like image 642
VGe0rge Avatar asked Dec 06 '14 23:12

VGe0rge


2 Answers

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 evaluated 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.

like image 127
5gon12eder Avatar answered Oct 12 '22 08:10

5gon12eder


Escaping the space works for me.

echo `date +%d.%m.%Y\ %R.%S.%3N` 
like image 22
DaniëlGu Avatar answered Oct 12 '22 09:10

DaniëlGu