This is the script:
#!/bin/bash
thedate=$(date)
var='Current date is $thedate'
echo $varThe 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 $varAlso, 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.
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 $varNote 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 $varIt would be better not to use variables, but define a function:-
cdate() { echo Current date is $(date); }
...
cdateOf 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