1

If I run the following command line on Ubuntu:

var="$(date +"%x %r %Z")"
echo var

I can get the desired output. But If I just run

date +%x %r %Z

I will be given errors:

date: extra operand ‘%r’

Try 'date --help' for more information.

So what is the date command corresponding to var="$(date +"%x %r %Z")"? Thanks.

  • 1
    The date command is date +"%x %r %Z" with the quotes on it so that it knows that all the % are part of it. – Terrance Sep 21 '18 at 5:14
4

You did not copy exactly the same command. You wrote date +"%x %r %Z" inside parentheses. This just work well outside. Otherwise, date has three arguments (+%x, %r and %Z), rather than one (+%x %r %Z).

From man bash :

When using the $(command) form, all characters between the parentheses make up the command; none are treated specially.
Command substitutions may be nested.

Parentheses are matched before evaluating the content, so the command is not split as $(date +%x, %r, %Z) .

Note :
You forgot the $ of echo $var.

  • Why does bash not interpret the assignment to be "$(date +" followed by %x %r %Z and then by ")"? We know var="aaa"bbb"ccc" ls is ok. – user5280911 Sep 21 '18 at 5:57
  • @user5280911 I updated my answer. – user285259 Sep 21 '18 at 6:16
1

So what is the date command corresponding to var="$(date +"%x %r %Z")"?

Well as already stated in another answer you missed to quote the options right, it should be at least:

date +"%x %r %Z"

This is needed because you are using white-spaces to keep the different information apart, the man page for date suggests using -, or _, with this you could omit the quoting all together in normal terminal, or you escape the white-spaces.


Examples:

  • using '-' as divider

    date +%x-%r%Z
    

    gives the following output:

    21.09.2018-11:30:15 CEST
    
  • using '_' as divider

    date +%x_%r%Z
    

    gives the following output:

    21.09.2018_11:30:15 CEST
    
  • using escaped white-spaces as divider

    date +%x\ %r%Z
    

    gives the following output:

    21.09.2018 11:30:15 CEST
    
  • using no dividers at all

    date +%x%r%Z
    

    gives the following output:

    21.09.201811:30:15 CEST
    

Remainder for a special use case. When you try to incorporate date into a crontab command, you need to escape the % sign too. So as undivided information the command would look like this (Before mentioned rules apply for escaping still):

date +\%x\%r\%Z

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.