Bash: 如何将变量的内容调用或修改到命令中?

Bash: How to invoke or ammend the contents of a variable onto a command?

关于这个问题的已接受答案(将 STDOUT 重定向到新 window,将 STDERR 重定向到相同的新 window 一个日志文件),我有一个 bash 脚本,它使用这种输出处理,如下所示,很多(感谢@hek2mgl!)。不是在所有命令上,只是在需要更改输出的命令上。例如,要将测试消息发送到新的 window 和日志文件,以及相应的错误处理,这非常有效(同样,正如在另一个线程上讨论的那样):

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)

但是。而不是 copy/pasting 该行在 bash 脚本中需要的地方一遍又一遍地处理输出,有没有一种方法可以在变量中设置所需的输出,然后将其调用到某些命令在哪里 nessecary?

因此,为了说明,将所需的输出设置放入:$outputHandling,如下所示:

$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)"

如何使用命令 invoke/ammend 这个?

这是我在用我极其有限的知识进行了非常老套的替换尝试后所能得到的最接近的结果(即不起作用,因为它正在打印变量),但希望表明我正在尝试做什么?

#!/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 为 noobing/amateurism!

道歉

我认为您正在寻找的是 shell 内置 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.

尝试将 eval 命令放在您想要实现问题中描述的效果的行的开头:

#!/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}