1

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.

bash

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.

stdout

analysis done by cmccabe on
07/12/16

desired result (analysis)

analysis done by cmccabe on
07/12/16
08:31:32 AM

2 Answers 2

1

&& (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
0
0

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .