Whenever I run a command in bash CLI, I get the right output
date %Y%-m%d%j%M%S
202111063103528
However, when I run this in a bash script, I am not getting a simple number that I can use in a later variable. I'm ultimately wanting to use this to backup old CSV files I've generated. e.g.
#Doesn't print out correct date
DATE='date %Y%-m%d%j%M%S'
echo $DATE
# Ultimately, wanting to feed that $DATE string here
if [ -f "$CSV_OUTFILE" ]; then
echo "CSV file already exists. Renaming $CSV_OUTFILE to $CSV_OUTFILE.$DATE"
mv $CSV_OUTFILE $CSV_OUTFILE.$DATE
exit 1
fi
Any suggestions on what I am doing wrong?
CodePudding user response:
You assigned the string date %Y%-m%d%j%M%S
to $DATE
. It contains a space, so using $DATE
in mv
without double quotes expands it to two words.
Use backquotes instead of quotes to capture the output of a command:
DATE=`date %Y%-m%d%j%M%S`
Or, better, use the $(...)
syntax (better because it can be nested):
DATE=$(date %Y%-m%d%j%M%S)