0

I'm trying to redirect the stdout and stderr to a log file. The filename should be created dynamically with current timestamp.

I can create the filename with the following command:

$ date +%Y-%m-%d_%H-%M-%S.txt
2018-04-10_16-55-55.txt

So I want to do something like this:

mycommand &> (date +%Y-%m-%d_%H-%M-%S.txt)

But this doesn't work (-bash: syntax error near unexpected token('`)

2

Yes, you will need to use a command substitution:

mycommand &> "$(date +%Y-%m-%d_%H-%M-%S.txt)"

Which is bash-speak for

mycommand  >"$(date +%Y-%m-%d_%H-%M-%S.txt)" 2>&1

Which is the same as

mycommand  >"$(date +%F_%H-%M-%S.txt)" 2>&1

(%F is the same as %Y-%m-%d)

A command substitution, $(...), will be replaced by the output of the command inside.

What you used was a sub-shell, (...). A sub-shell can't accept redirections like that.

1

Try this:

today=`date +%Y-%m-%d_%H-%M-%S`; mycommand > ${today}.txt 2>&1

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.