23

How do I print a formatted system date + hostname using printf in bash.

Something like printf "%s:%s\n" date hostname?

1 Answer 1

43
printf "%s:%s\n" "$(date)" "$(hostname)"
Sign up to request clarification or add additional context in comments.

6 Comments

Or more succinctly, thus: printf "$(date):$(hostname)\n"
@devnull that was cute and simple.
Instead of invoking a subshell with date in it, why not simply rely on the date format of bash's built-in implementation of printf(1)? For example: printf '%(%a %b %d %T %Z %Y)T:%s\n' -1 $(hostname)
@devnull: that can be problematic. "printf interprets escape sequences and format specifiers in the format string. If variables are included, any escape sequences or format specifiers in the data will be interpreted too, when you most likely wanted to treat it as data.". From github.com/koalaman/shellcheck/wiki/SC2059
@devnull aside from what was already pointed out, doesn't that defeat the purpose of printf? There's no (string) format whatsoever in your example.
|

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.