How can I make Bash interpret the contents of a variable as I/O redirects and not simply pass those contents to the command being executed. Take this script for example:
#!/bin/bash
test "$1" == '--log' && LOGGING="2>&1 | tee time.log" || LOGGING=""
date $LOGGING
The desired behavior is that when I run this script with the --log option bash wil execute
$ date 2>&1 | tee time.log
If I don't specify --log then it simply outputs date without creating a log. Instead it passes the contents of $LOGGING to date as a CLI argument resulting in an error:
date: extra operand `|' Try `date
--help' for more information.
Is there way to do this without writing something like
#!/bin/bash
test "$1" == '--log' && date 2>&1 | tee time.log || date
The actual application is obviously much more complicated than just calling "date" so I'd like to avoid copying and pasting that command twice in an if else just to append the redirect and logging commands.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…