2

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 `(')

1

2 Answers 2

5

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
1
  • Using bash on CentOS, I needed to escape the % symbols, like this: \%. Commented Oct 8, 2019 at 17:13

You must log in to answer this question.

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