假设我有一个如下脚本:
useless.sh
echo "This Is Error" 1>&2
echo "This Is Output"
Run Code Online (Sandbox Code Playgroud)
我有另一个shell脚本:
alsoUseless.sh
./useless.sh | sed 's/Output/Useless/'
Run Code Online (Sandbox Code Playgroud)
我想将"This Is Error"或者useless.sh中的任何其他stderr捕获到变量中.我们称之为ERROR.
请注意,我正在使用stdout.我想继续使用stdout,因此在这种情况下将stderr重定向到stdout是没有用的.
所以,基本上,我想做
./useless.sh 2> $ERROR | ...
Run Code Online (Sandbox Code Playgroud)
但这显然不起作用.
我也知道我能做到
./useless.sh 2> /tmp/Error
ERROR=`cat /tmp/Error`
Run Code Online (Sandbox Code Playgroud)
但那是丑陋和不必要的.
不幸的是,如果没有答案出现在这里,那就是我将要做的事情.
我希望还有另一种方式.
有没有更好的想法?
我有一些shell命令.我想将输出写入标准输出并将其保存到变量中.我想用一个命令来解决它.我试过这些东西.
ls > $VAR # redirects the output to file which name is stored in $VAR
ls | tee -a $VAR # writes to standard output as well as in file which name is stored in $VAR
VAR=`ls` # output into $VAR, but it is not sent to standard output
VAR=`ls`;echo $VAR # ok, it works but these are two commands
Run Code Online (Sandbox Code Playgroud)
任何的想法?
说我想要echo一些东西并在变量中捕获它,同时我在屏幕上看到它.
echo "hello" | tee tmp_file
var=$(< tmp_file)
Run Code Online (Sandbox Code Playgroud)
所以现在我可以hello在终端中看到并将其保存到变量中$var.
但是,有没有办法在不使用临时文件的情况下执行此操作?tee似乎不是解决方案,因为它说(从man tee)读取标准输入并写入标准输出和文件,而这里它是标准输出的两倍.
如果这很重要,我在Bash 4.3中.
我正在运行单元测试,这可能需要一些时间才能完成,在bash shell中,这些测试在运行时打印输出.我希望打印此输出,并且我还希望将输出存储在变量中.但是,如果可能的话,我希望这些内容可以同时完成,就像tee写入文件时命令一样.也许tee在这种情况下工作......
所以我目前正在这样做:
output=$(ginkgo -r -cover)
echo "$output"
Run Code Online (Sandbox Code Playgroud)
但是,在所有测试运行之前,这显然不会打印单元测试输出.那么如何在测试运行时将输出打印出来,同时将输出存储在变量中呢?