0

When I assign in a bash script

DATE=`date`

and

TODAY=${DATE:4:7}

then TODAY contains "Jul 2 " instead of "Jul{2 spaces} ".

So I want to change the first space in $TODAY into two spaces.
How do I do that?
Or how can I avoid the first wrong assignment to $TODAY?

2
  • When I do it, TODAY contains "Jul<space><space>2<space>". Commented Jul 2, 2013 at 10:28
  • 4
    Make sure yo put $TODAY in quotes when you echo it, if you don't want spaces to be collapsed. Commented Jul 2, 2013 at 10:31

4 Answers 4

2

If you just want Jul 2, why not using date options?

$ date "+%b %-d"
Jul 2
Sign up to request clarification or add additional context in comments.

Comments

1

if you want current month followed by two spaces:

date +'%b  '

or, for the long name:

date +'%B  '

to assign the command to a variable just use $() operator like this:

DATE=$(date +'%b  ')

and print it like this

echo "$DATE is the current month, with more spaces\!"

Comments

1
  1. Quoting is the key.
  2. Use $(...) instead of backticks.

You'll find that spaces are preserved:

$ DATE="$(date)"
$ echo "${DATE}"
$ Tue Jul  2 11:43:21 GMT 2013
$ TODAY=${DATE:4:7}
$ echo "*${TODAY}*"
$ *Jul  2 *

Comments

1

use the date params to format the date how you want

date "+%b %_d"

will pad the day with space giving the 2 spaces you are after

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.