Bash Command Substitution doesn't work

This is the script:

#!/bin/bash
thedate=$(date)
var='Current date is $thedate'
echo $var

The output is Current date is $thedate and I'd like to make it show the date,what did I do wrong? Any help would be appreciated.

3 Answers

var='Current date is $thedate'

Variables don't expand within single quotes, so this assigns a string containing the literal text $thedate. You should use double quotes here to have the variable expand.

echo $var

Also, here, you should use double quotes around the variable to prevent it from being subject to word splitting and pathname expansion, i.e. echo "$var". In this particular case you can mostly get away with not using quotes, since the date probably will not contain wildcard characters. But without quotes, e.g. the date string Fri Dec 7 20:41:21 EET 2018 would output as Fri Dec 7 20:41:21 EET 2018, that is, the double space after the month name would be collapsed to a single space.

3

The problem is that bash expands environment variables only once, unless you use eval, which causes the command line to be parsed twice:

eval echo $var

Note that the date and time displayed are those current when thedate is set, not when $var is referenced. To display the current time when $var is referenced, you need:-

var='Current date is $(date)'
eval echo $var

It would be better not to use variables, but define a function:-

cdate() { echo Current date is $(date); }
...
cdate

Of course, it is better still not to use echo, but let date itself add the extra text:

cdate() { date +"Current date is %c"; }

This doesn't output quite the same format as the date default, but there is no format specifier for the default.

Use double quotes instead of single quotes. Bash will not expand variables when in single quotes.

2

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like