I am trying to print a log using bash that captures the some text, logged in user, date, and time and prints it to a file analysis.


echo "analysis done by" "$USER" "on" && date +"%D"  && date +"%r" > /home/analysis

However, currently only the time prints to analysis and the echo.... user and date print to stdout. Why is this the case, am I doing something wrong? Thanks.


analysis done by cmccabe on

desired result (analysis)

analysis done by cmccabe on
08:31:32 AM
up vote 1 down vote accepted

&& (like ;) is a command separator, and redirections work at command level, not at line level.

If you want a single redirection to apply to several commands at once, group them:

(echo "foo"; date +bar) > /path/to/file

{ echo "foo"; date +bar; } > /path/to/file

(In this particular case, it doesn't matter whether you use && or ;.)

Alternatively you can output a single line with everything:

echo "analysis done by $USER at $(date "+%D %r")" > /path/to/file

Add %n to the output format string for date where you want a new line.

date +"analysis done by $USER on%n%D%n%r" > /home/analysis

If there's a chance that $USER might include %:

echo "analysis done by $USER on$(date +%n%D%n%r)" > /home/analysis

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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