6

For example, I want to write a command that shows the system time&date.

Then I want the output be like this

The system time is Mon Jan 01 01:01:01 AST 2011.

I know the command that shows the system time is date but how to add "The system time is" at the front of the output?

should it be echo The system time is + %#%@^ + date stuff like that?

14

A simple way would be:

printf "The system time is %s.\n" "$(date)"

You could also use string interpolation:

echo "The system time is $(date)."
12

With GNU date:

date +"The system time is %a %b %d %T %Z %Y"
  • +1 for this because it's a single command rather than two. – Monty Harder Feb 14 '18 at 19:44
  • @MontyHarder: echo isn't really a command, though... – SilverWolf Feb 14 '18 at 21:24
  • What would you call echo, @seaturtle ? Perhaps "an often built-in, but sometimes external command"? – Jeff Schaller Feb 14 '18 at 21:25
  • Do any (relatively common) shells not have echo as a builtin? I thought it always was. – SilverWolf Feb 14 '18 at 21:26
  • I just think we're splitting hairs if you don't call "built-in commands" "commands", but something else. – Jeff Schaller Feb 14 '18 at 21:28
8

Straightforwardly:

date +"The system time is %c"
  • %c - locale's date and time
  • 1
    @Ulysses Unfortunately, you've already accepted another answer, apparently within an hour of asking the question. – Monty Harder Feb 14 '18 at 19:45
1

With Bash 4.2 and higher, you can use printf:

printf "The system time is %(%a %b %d %T %Z %Y)T\n"
0

In the old days, we did

echo The system time is `date`.

But the backticks for command substitution are deprecated these days. Use this instead

echo The system time is $(date).

(only 1 extra character to type). You don't need no stinking double quotes.

0

Trivially:

echo -n 'The system time is '; date

Requires echo that honours the -n switch, but you'd have to search deep to find a system where it does not (or use printf).

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.