2

Below is the output I am getting and also what I want as an output


$ date Wed Apr 11 08:41:35 UTC 2018 $ DATE=date $ $DATE Wed Apr 11 08:41:43 UTC 2018 $ echo 'TEST' TEST $ echo 'Today is $DATE' Today is $DATE $ echo Today is $DATE Today is date 

--> wanted output as : Today is Wed Apr 11 08:41:43 UTC 2018

1
  • DATE=$(date); echo "Today is $DATE" Commented Apr 11, 2018 at 8:54

2 Answers 2

5

Let analyse step by step what you have done. At the bottom I give you several way how to achieve what you want.

Step by step:

$ date Wed Apr 11 08:41:35 UTC 2018 

Here, you just executed the date command. Nothing more, nothing less.

$ DATE=date $ $DATE Wed Apr 11 08:41:43 UTC 2018 

In this part you stored the word date into the variable DATE. Next you execute the variable DATE as a command. As DATE=date you essentially just execute the date command.

$ echo 'TEST' TEST 

You successfully printed the word TEST on /dev/stdout.

$ echo 'Today is $DATE' Today is $DATE 

Here the fun starts. You try to print the content of DATE in a string. However you make use of single quotes '. Inside single quotes everything is preserved literally, without exception. (See here. This expalains why there is no parameter expansion going on and you print $DATE and not date.

$ echo Today is $DATE Today is date 

In this case there is parameter expansion going on. The parameter DATE contains the word date, so this is what you get. There is no command executed as this is not what you asked for.

So how can we achieve the wanted output?

What you are interested in is what is called command substitution. Command substitution can be achieved with $(command) or `command`. Bash performs the expansion of any of these two forms by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted. This gives us the following options :

$ DATE=$(date) $ echo "Today is $DATE" 

or

$ echo "Today is $(date)" 

Finally, you can use the date command directly:

$ date "+Today is %c" 
Sign up to request clarification or add additional context in comments.

Comments

2

In shell script if you want to store the output of a command you have to execute the command first and that command should be right hand side of = sign. When a command executes its outputs to standard output stores into the variable. Now see below:-

DATE=$(date) or DATE=`date` 

Now in the above, date command will execute on the right hand side of = and its output to standard output will be stored in variable DATE.

Hope this will help you.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.