Reputation: 821
Relating to the accepted answer of this question here (redirecting STDOUT to new window, STDERR to same new window and also a log file), I have a bash script that uses this sort of output handling, as below, a lot (thanks @hek2mgl!). Not on all commands, just the ones where changing the output is desired. For example, to send a test message to new window and log file, along with the commensurate error handling, this works great (again, as discussed on the other thread):
printf "Test.\n" 1> >(tee -a backup_log-task${currentTask}.txt >> /dev/pts/$windowID) 2> >(tee -a backup_log-task${currentTask}.txt backup_log-task${currentTask}-errors.txt >> /dev/pts/$windowID)
But. Instead of copy/pasting that line to handle the output over and over in the places in a bash script where it's desired, is there a way I can set the desired output in a variable and then invoke that onto certain commands where nessecary?
So, to illustrate, put the desired output settings into: $outputHandling
, like so:
$outputHandling="1> >(tee -a backup_log-task${currentTask}.txt >> /dev/pts/$windowID) 2> >(tee -a backup_log-task${currentTask}.txt backup_log-task${currentTask}-errors.txt >> /dev/pts/$windowID)"
How to invoke/ammend this with a command though?
This is as close as I could get after having very hackneyed attempts at substitution with my extremely limited knowledge (i.e. doesn't work, as it's printing the variable), but hopefully show's what I'm trying to do?
#!/bin/bash
currentTask=1
windowID=0
outputHandling="1> >(tee -a backup_log-task${currentTask}.txt >> /dev/pts/$windowID) 2> >(tee -a backup_log-task${currentTask}.txt backup_log-task${currentTask}-errors.txt >> /dev/pts/$windowID)"
# we want to run: printf "Test.\n" 1> >(tee -a backup_log-task${currentTask}.txt >> /dev/pts/$windowID) 2> >(tee -a backup_log-task${currentTask}.txt backup_log-task${currentTask}-errors.txt >> /dev/pts/$windowID)
printf "Test.\n" ${outputHandling}
PS apologies for the noobing/amateurism!
Upvotes: 2
Views: 83
Reputation: 866
I think what you are looking for is the shell builtin eval
:
$ eval --help
eval: eval [arg ...]
Execute arguments as a shell command.
Combine ARGs into a single string, use the result as input to the shell,
and execute the resulting commands.
Exit Status:
Returns exit status of command or success if command is null.
Try placing the eval
command at the beginning of the line that you want to achieve the effect you described in your question:
#!/bin/bash
currentTask=1
windowID=1
outputHandling="1> >(tee -a backup_log-task${currentTask}.txt >> /dev/pts/$windowID) 2> >(tee -a backup_log-task${currentTask}.txt backup_log-task${currentTask}-errors.txt >> /dev/pts/$windowID)"
# we want to run: printf "Test.\n" 1> >(tee -a backup_log-task${currentTask}.txt >> /dev/pts/$windowID) 2> >(tee -a backup_log-task${currentTask}.txt backup_log-task${currentTask}-errors.txt >> /dev/pts/$windowID)
eval printf "Test.\\n" ${outputHandling}
Upvotes: 2