Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why am I not getting the desired output

This is the problem and, why am I not getting output as Today is date(24/01/2024) pls resolve this, and explain why am I not getting date in the below command ?

ubuntu@ip-192.56.21.19:~$ date | echo "Today is"
Today is

I tried this but couldnot resolve this, help me.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is arguably off-topic for SO, but I’m treating it as a programming question about the shell.

You’re feeding the date as input to echo, but echo doesn’t do anything with its input; it’s completely ignored. You can send anything you like into it and all you get back is whatever you put on the command line:

$ echo 'boo!' | echo hi
hi
$ echo hello </etc/passwd
hello

etc, etc, etc.

You can do what you want in a number of ways. For instance, you could simply echo the Today is first and then call date afterward:

$ printf '%s ' 'Today is'; date
Today is Tue Jan 23 22:43:01 EST 2024

But most solutions would use command substitution to include the output of date as a string inside the command doing the echoing. For example:

$ printf 'Today is %s\n' "$(date)"
Today is Tue Jan 23 22:43:53 EST 2024

The "$(date)" construct runs date and is then replaced by whatever it outputs.

I used printf instead of echo, which is a best practice for shell programs; the behavior of echo is slightly inconsistent between shell implementations, and most of them don’t strictly adhere to the POSIX specification. printf is much more consistent, and the use of format specifiers means you don’t have to do as much interpolation, which otherwise might require miyying and matching types of quotation marks. You do have to supply your own newlines, but that also makes it easy to echo stuff without a newline, as in the first solution above.

If you want the date in a different format you can use the +formatstring parameter to date. Check out the strftime(3) man page for all the field options, but to get dd/mm/yyy use date +%d/%m/%Y.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading