0

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

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.