CrazyC
CrazyC

Reputation: 1896

Shell command date

I want to print date in the mm-dd-yy format in shell script. From shell terminal I can get it using the following command:

date +"%d-%m-%y"

But I want it in the shell script and in a variable which could then be appended to a file name. I tried the following:

#!/bin/sh
mydate=`"date +\"%m-%d-%Y\""'
echo "$mydate"

But it is giving an error date +"%d-%m-%y" is not found. Can anybody point out what mistake am I making?

Upvotes: 0

Views: 2378

Answers (4)

glenn jackman
glenn jackman

Reputation: 246744

You have advice about how to do it properly. The reason for the error is the first level of inner double quotes makes the entire command with arguments into a single word:

mydate=`"date +\"%m-%d-%Y\""'

You are trying to execute a command named:

date +"%m-%d-%Y"

and clearly no such command exists.

Upvotes: 2

Nagakishore Sidde
Nagakishore Sidde

Reputation: 2737

#!/bin/sh
mydate=`date +\"%m-%d-%Y\"`
mydate1=`date +%m-%d-%Y`
echo "$mydate"
echo "$mydate1"

Both approaches will work. But the first one will have the date value surrounded by double quotes, something like "09-29-2014".

Upvotes: 0

fedorqui
fedorqui

Reputation: 289495

Use

mydate=$(date "+%m-%d-%Y")

See this is a way to store a command in a variable: var=$(command). To use date, you define the format like date "+%format%place%holders", with + inside the double quotes.

$ mydate=$(date "+%m-%d-%Y")
$ echo $mydate
09-29-2014

Note it is preferred to use $() over ``, because it allows nesting multiple commands.

Upvotes: 2

ismail
ismail

Reputation: 47572

You don't need quotes

mydate=`date +%m-%d-%Y`

will work.

Upvotes: 3

Related Questions